json-lib——JsonConfig详细使用说明

在使用json-lib包中JSONObject.fromObject(bean,cfg)时,可能出现以下几种情况:

1、(防止自包含)转换的对象包含自身对象,或者对象A下面挂了对象B,对象B下面又挂了对象A,如果不设置取消环形结构,则那么会抛异常:"There is a cycle in the hierarchy!"

解决方法:

  在调用JSONObject.fromObject(bean,cfg)时,自定义JsonConfig:

JsonConfig cfg = new JsonConfig();
cfg.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);

然后将cfg对象传入fromObject方法中,这样,对象B下面挂的对象A就会被置为NULL。

 

2、(Date类型转化)JavaBean出现Date格式时,转化成json时会出现将其转化为:{"date":6,"day":3,"hours":21,"minutes":26,"month":0,"nanos":290000000,"seconds":31,"time":1452086791290,"timezoneOffset":-480,"year":116},这个不易处理,如果需要将Date转换为我们认识的“yyyy-MM-dd”格式,则需要自行创建时间转换器,并实现json-lib中的JsonValueProcessor接口,实现该接口中的两个方法(processArrayValue和processObjectValue):

JsonDateValueProcessor

  cfg.registerJsonValueProcessor(Date.class, new JsonDateValueProcessor());

  这样,对象下面如果有Date类型,转化出来变为“yyyy-MM-dd”格式。

 

3、(字段过滤)如果需要在转化过程中去除某些字段,则需要定义一些Excludes字段,具体使用如下:

  String[] EXCLUDES = new String[]{"A","B","C"};

  cfg.setExcludes(EXCLUDES);  

  这样,对象转化时,"A","B","C"会被去除,对象中这些字段转成json时会被删除。

 

4、(过滤器PropertyFilter使用)和3有点类似,但是PropertyFilter作用是为了过滤某些符合一些指定条件的属性,如:

cfg.setJsonPropertyFilter(new PropertyFilter() {
public boolean apply(Object source, String name, Object value) {
return value == null;//value为null时返回true,返回true的就是需要过滤调的
}
});

这样,对象转化出来后,生成的 json 字符串只包含非空的值。

5、其余的常见用法:

  • cfg.setIgnoreDefaultExcludes(true);  //默认为false,即过滤默认的key,改为true则不忽略
  • cfg.setJsonPropertyFilter(new IgnoreFieldProcessorImpl(true)); // 忽略掉集合对象 
  • cfg.setJsonPropertyFilter(new IgnoreFieldProcessorImpl(true, new String[]{"name"})); // 忽略掉name属性及集合对象 
json-lib——JsonConfig详细使用说明

猜你喜欢

转载自blog.csdn.net/tomcatAndOracle/article/details/80928080
今日推荐