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

fastjson 如何去掉 $ref,使用方法,不讲原理

2017-02-16 14:46 405 查看
fastjson 是一个 不错的json格式化工具,

但是在使用时,如果 碰到统一地址对象引用,就会用$ref替代 。

怎么去掉ref呢,

这里 有两种方法

1. 使用 

SerializerFeature 订制


如变代码引用 注释,部分

2.使用 

JSONObject.toJSON(map).toString()


多说一点,看下边  

String str ="testchar" ;

JSONObject.toJSONString(str) 返回   "\"testchat\"" ,多一套转移 引号
JSONObject.toJSON(str) 返回 "testchar"





这时不会把 文字转成 "\"testchat\'" ,'testchar'


package authdemo;

import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;

public class TestMyTest {

public static void main(String[] args) {
Map<String,Object> map = new HashMap<String, Object>() ;
Map<String,Object> inenermap = new HashMap<String, Object>() ;
inenermap.put("key1", "12131") ;

map.put("key3", "333") ;
map.put("inmap", inenermap) ;
map.put("in2", inenermap) ;

// SerializerFeature[] features = {
// SerializerFeature.WriteMapNullValue, // 输出空置字段
// SerializerFeature.WriteNullListAsEmpty, // list字段如果为null,输出为[],而不是null
// SerializerFeature.WriteNullNumberAsZero, // 数值字段如果为null,输出为0,而不是null
// SerializerFeature.WriteNullBooleanAsFalse, // Boolean字段如果为null,输出为false,而不是null
// SerializerFeature.WriteNullStringAsEmpty, // 字符类型字段如果为null,输出为"",而不是null
// SerializerFeature.DisableCircularReferenceDetect //TODO 有了这句就没有$ref了
// };

System.out.println( JSONObject.toJSON(map).toString());
System.out.println( JSONObject.toJSONString(map));

Object o = JSONObject.parseObject(JSONObject.toJSONString(map), Map.class) ;
Object o2 = JSONObject.parseObject(JSONObject.toJSON(map).toString(), Map.class) ;
System.out.println(o);
}

}



看看输出的不同 

解开上边 注释代码,输出结果都没有 $ref
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: