Object 转 json 工具类

/**
* 把数据对象转换成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;
}

posted @ 2016-03-18 09:06  Struts-pring  阅读(486)  评论(0编辑  收藏  举报