Java怎样高速构造JSON字符串

目标:依据key/value高速构造一个JSON字符串作为參数提交到web REST API服务上。
分别測试里阿里巴巴的FastJson和Google Gson,终于我採用了Google Gson来构造。


原因:
Google Gson来构造的JSON字符串里面。保留了传递參数key/value的顺序;
FastJson没有保留顺序(这个是符合JSON国际标准的,本身没有错误。

是SugarCRM REST API有bug,要求传递过来的參数是依照它的顺序要求的)。

Google Gson代码片段:

import com.google.gson.Gson;
...
  LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
        map.put("f1","xxx");
        map.put("f2","xxxx");
        map.put("f3","xxxxx");
        Gson gson = new Gson();
        String json = gson.toJson(map);

Alibaba FastJson代码片段:

import com.alibaba.fastjson.JSONObject;

JSONObject jsonObject = new JSONObject();  
        jsonObject.put("f1", "xxx");
        jsonObject.put("f2", "xxx");
        String json = jsonObject.toJSONString();
posted @ 2016-02-03 16:18  yxwkaifa  阅读(338)  评论(0编辑  收藏  举报