一、防止包自含
在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;
- }
- });
- JsonConfig config = new JsonConfig();
- // 解决延迟加载产生异常的问题
- config.setExcludes(new String[] { "handler", "hibernateLazyInitializer" });
- 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;
- }
- });