V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
hellomsg
V2EX  ›  Java

fastJson 将对象转换为 json 字符串

  •  
  •   hellomsg · Sep 1, 2015 · 6695 views
    This topic created in 3893 days ago, the information mentioned may be changed or developed.

    测试代码:

    // 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 replies    2015-09-02 00:35:52 +08:00
    hellomsg
        2
    hellomsg  
    OP
       Sep 1, 2015
    @kaifeii 非常感谢
    ophunter
        3
    ophunter  
       Sep 1, 2015
    友情提醒,如果能用 Gson 就别用 fastjson
    rockyou12
        4
    rockyou12  
       Sep 1, 2015
    @ophunter 为什么?不是说 fastjson 效率要高很多嘛?而且 api 我都看过,感觉用起来不会差很多
    Ouyangan
        5
    Ouyangan  
       Sep 1, 2015
    一般用 Gson...大多数就用到 to/from
    pixstone
        6
    pixstone  
       Sep 2, 2015 via iPhone
    fastjson 有坑 需要规避
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2985 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 67ms · UTC 15:00 · PVG 23:00 · LAX 08:00 · JFK 11:00
    ♥ Do have faith in what you're doing.