1. 程式人生 > >Java如何快速構造JSON字串

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);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

Alibaba FastJson程式碼片段:

import com.alibaba.fastjson.JSONObject;JSONObject jsonObject = new JSONObject()
        jsonObject.put("f1", "xxx");        jsonObject.put("f2", "xxx");        String json = jsonObject.toJSONString();
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6