您的位置:首页 > Web前端 > JavaScript

json-lib之jsonConfig详细使用

2014-09-13 23:05 477 查看
一、防止包自含

在JSON-LIB中,要转换的对象包含自身对象时,会抛出异常There is a cycle in the hierarchy,解决办法:

jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);
二、自定义要被转换的字段

config.setJsonPropertyFilter(new PropertyFilter() {

@Override
public boolean apply(Object source, String name, Object value) {
// TODO Auto-generated method stub
if (name.equals("id") || name.equals("serialNumber")
|| name.equals("productName")
|| name.equals("emailAddress")
|| name.equals("applySatus") || name.equals("remark")
|| name.equals("applyStatusLabel")
|| name.equals("applyDate")) {
<span style="white-space:pre">					</span>//这些字段会被转换
return false;
}
return true;
}
});
三、解决延迟加载产生异常的问题(net.sf.json.JSONException: java.lang.reflect.InvocationTargetException)

JsonConfig config = new JsonConfig();
// 解决延迟加载产生异常的问题
config.setExcludes(new String[] { "handler", "hibernateLazyInitializer" });
四、解决数据库查询结果中,Date转换的问题(net.sf.json.JSONException: java.lang.reflect.InvocationTargetException)

config.registerJsonValueProcessor(java.util.Date.class,
new JsonValueProcessor() {
@Override
public Object processArrayValue(Object obj,
JsonConfig jsonconfig) {
return null;
}

@Override
public Object processObjectValue(String key, Object value,
JsonConfig jsonConfig) {
if (value == null)
return "";
// 注意:在判断几个父子级类型时要先判断子类型再判断父类型
if (value instanceof java.sql.Date) {
String str = DateUtil.dateToStr((java.util.Date) value,
"yyyy-MM-dd");//这里是我封装的工具,可以使用SimpleDateFormat代替,一样
return str;
} else if (value instanceof java.sql.Timestamp
|| value instanceof java.util.Date) {
String str = DateUtil.dateToStr((java.util.Date) value,
"yyyy-MM-dd HH:mm:ss");
return str;
}
return value.toString();
}
});
五、结果转换

有些字段的类型是枚举类型,可以在转换的时候将值设置为枚举类的value或者是label

config.registerJsonValueProcessor(ApproveStateType.class,
new JsonValueProcessor() {

@Override
public Object processObjectValue(String key, Object value,
JsonConfig jsonConfig) {
// TODO Auto-generated method stub
if (value instanceof ApproveStateType) {
ApproveStateType tmpValue = (ApproveStateType) value;
return tmpValue.getValue();
}
return value.toString();
}

@Override
public Object processArrayValue(Object arg0, JsonConfig arg1) {
// TODO Auto-generated method stub
return null;
}
});
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: