list转换为JsonArray时,使用JsonValueProcessor处理有关数据类型

来源:互联网 发布:ubuntu 重置系统命令 编辑:程序博客网 时间:2024/05/21 18:34

使用JSONArray jsonarray = JSONArray.fromObject(list);可以轻松将list转换为array,但是当list中含有data类型的数据的时候,就会转换不正确,例如将createTime在数据库中为dateTime类型,被转换成了"createTime":"date":26,"day":2,"hours":0,"minutes":0,"month":10,"nanos":0,"seconds":0,"time":1385395200000,"timezoneOffset":-480,"year":113},不是需要的“yyyy-MM-dd HH:mm:ss”格式.

使用JsonValueProcesscor进行配置。JsonValueProcessor是interface,实现该接口,定义List转换为Json格式时,如何转换Date类型的数据。

package util;

 

importjava.text.SimpleDateFormat;

import java.util.Date;

import java.util.Locale;

 

import net.sf.json.JsonConfig;

import net.sf.json.processors.JsonValueProcessor;

 

public classJsonDateValueProcessor implements JsonValueProcessor {

        privateString pattern = "yyyy-MM-dd HH:mm:ss";

 

        //定义两个构造函数,通过第二个构造函数可以自定义时间格式化字符串

        publicJsonDateValueProcessor() {

               super();

        }

 

        publicJsonDateValueProcessor(String format) {

               this.pattern= format;

 

        }

 

        publicObject processArrayValue(Object arg0, JsonConfig arg1) {

               //TODO Auto-generated method stub

               returnprocess(arg0);

        }

 

        publicObject processObjectValue(String arg0, Object arg1, JsonConfig arg2) {

               //TODO Auto-generated method stub

               returnprocess(arg1);

        }

        privateObject process(Object val){

               if(valinstanceof Date&& val!=null){

                       SimpleDateFormatsdf=new SimpleDateFormat(this.pattern,Locale.CHINESE);

                       returnsdf.format(val);

               }else

                       returnval==null?"":val.toString();

              

        }

 

}


在使用JSONArray.fromObject()

JsonConfig config = newJsonConfig();        

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

               JSONArray.fromObject(readlist,config);

在使用JSONArray.fromObject(list),如果list是hibernate返回的实体结果,实体有级联关系,则极有可能抛出net.sf.json.JSONException: There is a cycle in the hierarchy异常。,所以需要使用JSONValueProcessor处理有关嵌套的字段。例如项目中的Paper这个类,

entity如下:


hbm.xml文件如下:



可以看出pps pqs npps quotepapers这4个字段都是关联了其他表的,这样会

JSONArray会无线循环封装。抛出异常。解决方法如下:


如何在myeclipse中运行main函数时,为main函数加入运行参数?