fastJson 将对象转换为 json 字符串

2015-09-01 09:59:02 +08:00
 hellomsg

测试代码:

// jackson
private static ObjectMapper om = new ObjectMapper ();
public static String objectToString (Object obj ) throws IOException{
    return om.writeValueAsString (obj );
}

@Test
public void test1 () throws IOException {
    Map<String, Object> map = new HashMap<String, Object>();

    Map<String, String> map2 = new HashMap<String, String>();
    map2.put ("name", "1");
    map2.put ("age", "12");
    map.put ("att", map2 );

    List<String> list = new ArrayList<String>();
    list.add ("hi");list.add ("hello");
    map.put ("list", list );

    List<Map<String, String>> confuselist = new ArrayList<Map<String, String>>();
    Map<String, String> map3 = new HashMap<String, String>();
    map3.put ("name", "1");
    map3.put ("age", "12");
    confuselist.add (map3 );
    confuselist.add (map2 );
    map.put ("confuselist", confuselist );

    Object array = Array.newInstance (String.class, 10 );
    Array.set (array, 0, "a");
    Array.set (array, 1, "b");
    Array.set (array, 2, "c");
    map.put ("array", array );
    // 使用 jackson
    System.out.println (objectToString (map ));
    // 使用 fastJson
    System.out.println (JSON.toJSONString (map ));
}

输出:

{"att":{"age":"12","name":"1"},"list":["hi","hello"],"confuselist":[{"age":"12","name":"1"},    {"age":"12","name":"1"}],"array":["a","b","c",null,null,null,null,null,null,null]}

{"att":{"age":"12","name":"1"},"list":["hi","hello"],"confuselist":[{"age":"12","name":"1"},{"$ref":"$.att"}],"array":["a","b","c",null,null,null,null,null,null,null]}

fastJson 对相同的对象使用引用标记节省字符串体积吗?有没有办法不用引用。

6228 次点击
所在节点    Java
6 条回复
kaifeii
2015-09-01 11:03:08 +08:00
hellomsg
2015-09-01 11:11:15 +08:00
@kaifeii 非常感谢
ophunter
2015-09-01 13:56:58 +08:00
友情提醒,如果能用 Gson 就别用 fastjson
rockyou12
2015-09-01 14:27:36 +08:00
@ophunter 为什么?不是说 fastjson 效率要高很多嘛?而且 api 我都看过,感觉用起来不会差很多
Ouyangan
2015-09-01 16:09:02 +08:00
一般用 Gson...大多数就用到 to/from
pixstone
2015-09-02 00:35:52 +08:00
fastjson 有坑 需要规避

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/217482

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX