日期:2014-05-16  浏览次数:20304 次

解决json-lib-1.5.jar处理存在级联关系的pojo的json数据生成的问题

使用json-lib-1.5.jar来处理java和json的转换的确给我们带来了不少的方便,但是在处理存在级联关系的pojo时,使用fromObject时就会报:net.sf.json.JSONException: There is a cycle in the hierarchy!,使得生成json掉入了级联的循环陷阱中,但是pojo肯定会存在级联关系,怎么解决这个问题呢?

当然你可以拼写字符串,也可以使用map,但是仍然不是非常方便,需要一个个的处理属性。其实json.jar给我们提供了一个相关的处理来应对这样的情况,就是通过JSON的配置类JsonConfig。如下代码所示:

JsonConfig jsonConfig = new JsonConfig();
jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);
String[] excludes = { "poNewsArticle", "class" };
jsonConfig.setExcludes(excludes);
PoNewsComment c=newsService.getCommentById(id);
JSONObject jsonObject = JSONObject.fromObject(c);
System.out.println(jsonObject.toString());

?

PoNewsComment.java

public class PoNewsComment implements java.io.Serializable {

	// Fields

	private Integer commentId;
	private PoNewsArticle poNewsArticle;//关联的新闻的pojo
	private String comment;
	private String commenter;
	private Date commentTime;
	private short commentStatus;
	private String commenterIp;
//省略set、get方法
}

?其实其他的情况都可以使用JsonConfig来处理,包括时间转换,数据类型的转换等等。下一篇将介绍一个操作json的通用工具类。

?