## 1.对象、Map转成json
测试需要的实体类一属性如下:
User:
private String userName;//用户名
private String password;//密码
private Set<Role> roles = new HashSet<Role>();//角色与用户 多对多
Role:
private String name;//
private Set<User> users = new HashSet<User>(0);//角色与用户 多对多
在这里插入代码片
测试实现
@Test
public void testObjToJson() {//对象转json和map转json是一样的
//测试对象转json
User user = new User();
user.setUserName("张阿三");
user.setPassword("123");
String jsonString = JSON.toJSONString(user);
System.out.println(jsonString);
}
@Test
public void testMapToJson() {//{"password":"123","username":"hnh"}
HashMap hashMap = new HashMap();
hashMap.put("username", "hnh");
hashMap.put("password", "123");
String jsonString = JSON.toJSONString(hashMap);
System.out.println(jsonString);
}
2.List转接送json
如果list中存两次同一个对象,那么最终转成的会出现引用的情况:
@Test
public void testArrList() {
User user = new User();
user.setUserName("张阿三");
user.setPassword("123");
User user1 = new User();
user1.setUserName("王五");
user1.setPassword("456");
ArrayList list = new ArrayList();
list.add(user);
list.add(user1);
list.add(user);//再添加一个相同的对象的时候 就会出现地址引用{"$ref":"$[0]"}
// String jsonString = JSON.toJSONString(list);
//SerializerFeature.DisableCircularReferenceDetect 关闭循环引用
String jsonString = JSON.toJSONString(list,SerializerFeature.DisableCircularReferenceDetect);//解决地址引用问题
System.out.println(jsonString);
}
解决的途径是:转list的时候,后面加上SerializerFeature.DisableCircularReferenceDetect,就会解决对象引用的问题了。
3.对象中“你中有我及我中有你”(比如User中有Role的集合,Role中有User的集合)的时候怎么解决:
如果直接JSON.toJSONString(user);这样转的话,就会崩,因为会出现“不断的找”的情况。
如果是转user的话可以在User类中加上下面这个注解
@JSONField(serialize=false)
private Set users = new HashSet(0);
这样解析的时候,Role中的user集合就不会在做解析。但是这个有个问题,就是如果换成解析role,我们有需要改代码。
这时可以使用SimplePropertyPreFilter。
//参数中写上的字段就做解析 不写的字段就不做解析了 SimplePropertyPreFilter filter = new
SimplePropertyPreFilter(“password”,“roles”,“name”,“userName”);
@Test
public void testArrList1() {//对象之间互相引用的问题 ( 你中有我 我中有你)
HashSet<User> users = new HashSet<User>();
HashSet<Role> roles = new HashSet<Role>();
Role role = new Role();
role.setName("测试人员");
roles.add(role);
User user1 = new User();
user1.setUserName("王五");
user1.setPassword("456");
users.add(user1);
user1.setRoles(roles);
role.setUsers(users);
//{"password":"456","roles":[{"modules":[],"name":"测试人员"}],"userName":"王五"}
//参数中写上的字段就做解析 不写的字段就不做解析了
SimplePropertyPreFilter filter = new SimplePropertyPreFilter("password","roles","name","userName");
//SerializerFeature.DisableCircularReferenceDetect(关闭循环) 不能解决 因为你中有我 我中有你 无穷尽
String jsonString = JSON.toJSONString(user1,filter,SerializerFeature.DisableCircularReferenceDetect);
System.out.println(jsonString);
}