V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
hellomsg
V2EX  ›  Java

fastJson 将对象转换为 json 字符串

  •  
  •   hellomsg · 2015-09-01 09:59:02 +08:00 · 6251 次点击
    这是一个创建于 3401 天前的主题,其中的信息可能已经有所发展或是发生改变。

    测试代码:

    // 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 对相同的对象使用引用标记节省字符串体积吗?有没有办法不用引用。

    6 条回复    2015-09-02 00:35:52 +08:00
    kaifeii
        1
    kaifeii  
       2015-09-01 11:03:08 +08:00   ❤️ 2
    hellomsg
        2
    hellomsg  
    OP
       2015-09-01 11:11:15 +08:00
    @kaifeii 非常感谢
    ophunter
        3
    ophunter  
       2015-09-01 13:56:58 +08:00
    友情提醒,如果能用 Gson 就别用 fastjson
    rockyou12
        4
    rockyou12  
       2015-09-01 14:27:36 +08:00
    @ophunter 为什么?不是说 fastjson 效率要高很多嘛?而且 api 我都看过,感觉用起来不会差很多
    Ouyangan
        5
    Ouyangan  
       2015-09-01 16:09:02 +08:00
    一般用 Gson...大多数就用到 to/from
    pixstone
        6
    pixstone  
       2015-09-02 00:35:52 +08:00 via iPhone
    fastjson 有坑 需要规避
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   5768 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 06:35 · PVG 14:35 · LAX 22:35 · JFK 01:35
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.