首页 > Web开发 > 详细

Object 转 json 工具类

时间:2016-03-18 09:32:50      阅读:324      评论:0      收藏:0      [点我收藏+]

/**
* 把数据对象转换成json字符串 DTO对象形如:{"id" : idValue, "name" : nameValue, ...}
* 数组对象形如:[{}, {}, {}, ...] map对象形如:{key1 : {"id" : idValue, "name" :
* nameValue, ...}, key2 : {}, ...}
*
* @param object
* @return
*/
public static String getJSONString(Object object) {
String jsonString = null;
// 属性值处理器
JsonConfig jsonConfig = new JsonConfig();
try{
jsonConfig.registerJsonValueProcessor(Date.class,new JsonDateValueProcessor());
//整形转换为字符串
jsonConfig.registerJsonValueProcessor(Integer.class, new IntegerValueProcessor());
if (object != null) {
if (object instanceof Collection || object instanceof Object[]) {
jsonString = JSONArray.fromObject(object, jsonConfig)
.toString();
} else {
jsonString = JSONObject.fromObject(object, jsonConfig)
.toString();
}
}
} catch(Exception ex){
ex.printStackTrace();
}
return jsonString == null ? "{}" : jsonString;
}

Object 转 json 工具类

原文:http://www.cnblogs.com/Struts-pring/p/5290744.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!