最近毕设需要给App端写接口,一般都是返回json格式的数据,但是将对象转为json时总是报错,之前做后台界面使用ajax的时候也出现过。
一、需求:返回学生信息、学生对应部门信息、学生对应班级信息json数据
(1)实体类
public class Student implements java.io.Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private Integer id;
private String stuNum;
private String stuName;
private String sex;
private Timestamp birthday;
private String grade;
private String photo;
private Department department;
private Class_ class_;
private Role role;
(2)找到学生对象,调用一个自己写的方法将对象转为json数据并输出
Student stuFind=userFind.getStudent();
JsonUtil.toJson(ServletActionContext.getResponse(), stuFind);
(3)转为json并输出的方法
public class JsonUtil {
//使用Gson--->xx转化成json
public static void toJson(HttpServletResponse response, Object data)
throws IOException {
Gson gson = new Gson();
String result = gson.toJson(data);
response.setContentType("text/json; charset=utf-8");
response.setHeader("Cache-Control", "no-cache"); //取消浏览器缓存
PrintWriter out = response.getWriter();
System.out.println(result);
out.print(result);
out.flush();
out.close();
}
(4)错误信息,栈溢出,因为学生还关联了部门、班级等信息,它会根据关联信息继续查找,导致栈溢出或者死循环的问题
二、解决方法
(1)将学生对应的role、 department和role排除
JsonConfig jc_student=new JsonConfig();
jc_student.setJsonPropertyFilter(new PropertyFilter() {
@Override
public boolean apply(Object class_, String property, Object proValue) {
if(property.equals("role")||property.equals("department")||property.equals("class_")){
return true;
}
else{
return false;
}
}
});
JSONArray json_student =JSONArray.fromObject(stuFind,jc_student);
JsonUtil.toJson(ServletActionContext.getResponse(), json_student);
(2)测试结果成功
三、还需要返回学生对应的部门和班级,但是没次都是通过上面的方法将关联的外键属性去除掉有些麻烦
(1)考虑写一个公共的方法,将对应对象的管理外键属性去掉
//过滤掉关联的外键
public static JSONObject jsonFilter(Object obj, String[] filterNames){
JsonConfig jsonConfig = new JsonConfig();
jsonConfig.setIgnoreDefaultExcludes(false);
jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT); //防止自包含
if(filterNames != null){
//这里是核心,过滤掉不想使用的属性
jsonConfig .setExcludes(filterNames) ;
}
JSONObject jsonObj = JSONObject.fromObject(obj, jsonConfig);
return jsonObj;
}
(2)实现
Student stuFind=userFind.getStudent();
String[] stuProperty={"role","department","class_"};
map.put("student", JsonUtil.jsonFilter(stuFind, stuProperty));
//部门
Department deptFind=stuFind.getDepartment();
String[] deptProperty={"children","parent","students","teachers","classes","courses"};
map.put("department", JsonUtil.jsonFilter(deptFind, deptProperty));
//班级
Class_ classFind=stuFind.getClass_();
String[] classProperty={"department","students"};
map.put("class_", JsonUtil.jsonFilter(classFind, classProperty));
JsonUtil.toJson(ServletActionContext.getResponse(), map);
(3)测试成功,学生、部门、班级
四、总结
遇到问题总是好的,可以学到更多的东西。总之,还有很多要去学习的,加油。