Json解析

1.FastJson解析
(1.)导入fastJson包
(2)创建一个javabean类

例:

public class FastJsonTest {

		
	//将json对象转换为字符串
	@Test
	public void testJavaToJson() {
		
	 
		/*Javabean*/
      User user =new User();
       user.setUage(18);
       user.setUname("zhangsan");
      user.setUpwd("123456");
      user.setUserId(1);


       User user1 =new User();
       user1.setUage(20);
       user1.setUname("haha");
      user1.setUpwd("1237896");
      user1.setUserId(2);

       User user2 =new User();
       user2.setUage(19);
       user2.setUname("hehe");
      user2.setUpwd("1278946");
      user2.setUserId(4);
	
      		
  
	/*List*/
    	 List <String> list=new ArrayList<>();
      	 list.add("cc");
        	list.add("pp");
       	 list.add("yy");
	
    
	
	
   	  List <String> list2=new ArrayList<>();
    	  list.add(user);
      	list.add(user1);
     	 list.add(user2);

    

  
	Map<String,Object>map=new HashMap<>();
	 map.("user1",user);		//把user对象添加到容器map里
	map.("list1","list"); 
	map.("list2",list2);
	

	String json=toJSONString(user);
	String json1=toJSONString(list);
	String json2=toJSONString(list2);
	String json3=toJSONString(map);

	System.out.println(user);
	System.out.println(list);
	System.out.println(list2);
	System.out.println(map);

	




	//将字符串转换为对象
	
	@Test
	public void testJsonToJava() {
	
	String json=String json = "{\"userId\":1,\"uname\":\"zhangsan\",\"upwd\":\"123456\",\"uage\":18}";
	String json2 = "[\"aa\",\"bb\",\"cc\"]";
	String json3 = "[{\"userId\":1,\"uname\":\"zhangsan\",\"upwd\":\"123456\",\"uage\":18},{\"userId\":2,\"uname\":\"lisi\",\"up\"111223\",\"uage\":19},{\"userId\":3,\"uname\":\"wangeu\",\"upwd\":\"65432\",\"uage\":20}]";
	
	User user=JSON.parseObject(json,User.class);
	List<String>list=JSON.parseObject(json2,String.class);
	List<User>list2=JSON.parseObject(json3,User.class);
	

	}
	






	}



上一篇:Hibernate 中对象 set 属性时自动保存入库的问题


下一篇:【SQL】表A多个字段,关联表B一个字段说明