java生成Json工具之JsonSimple的使用


json-simple是由是Google開發的Java JSON解析框架,基於Apache協議。目前版本為1.1

項目主頁:https://code.google.com/p/json-simple/#JSON.simple_in_Publications

Java實體類和JSON對象之間的映射如下表:

JSON Java
string java.lang.String
number java.lang.Number
true|false java.lang.Boolean
null null
array java.util.List
object java.util.Map

從此表中我們可以看出,當解析json對象映射到java實體類時,是從左邊到右邊。從左邊到右邊是Java實體類到json字符。在編碼時默認的JSONArray是繼承了ArrayList實現了List接口,JSONObject是繼承了HashMap實現 了Map接口。jsonsimple默認的只支持表中的幾種類型轉換為json如果是一個復雜的對象要轉換成Json字符,該類要實現JSONAware接口或者是JSONStreamAware。實現了以上兩個接口后必須要重寫toJSONString()或者writeJSONString()。來輸出json字符。

好了,話不多說,看例子吧!

  • Example 1-1 - Encode a JSON object
       // 是java中HashMap的子類
        JSONObject json = new JSONObject();
        json.put("name", "張曉天");
        json.put("boolean", true);
        json.put("null", null);
        json.put("num", 7);
        json.put("double", 34.5);
        printJson(json.toJSONString());
        // {"num":7,"name":"張曉天","boolean":true,"double":34.5,"null":null}
  • Example 1-2 - Encode a JSON object – Streaming
JSONObject obj = new JSONObject();
        obj.put("name", "foo");
        obj.put("num", new Integer(100));
        obj.put("balance", new Double(1000.21));
        obj.put("is_vip", new Boolean(true));
        obj.put("nickname", null);
        StringWriter out = new StringWriter();
        try {
            obj.writeJSONString(out);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        String jsonText = out.toString();
        printJson(jsonText);
        // {"balance":1000.21,"num":100,"nickname":null,"is_vip":true,"name":"foo"}
  • Example 2-1 - Encode a JSON array
      JSONArray list = new JSONArray();
        list.add("foot");
        list.add("張曉天");
        list.add(false);
        list.add(6.9);
        list.add(7);
        list.add(null);
        printJson(list.toJSONString());
        // ["foot","張曉天",false,6.9,7,null]
  • Example 2-2 - Encode a JSON array - Using List
      List list = new LinkedList<>();
        list.add("foot");
        list.add("張曉天");
        list.add(false);
        list.add(6.9);
        list.add(7);
        list.add(null);
        String jsonText = JSONValue.toJSONString(list);
        printJson(jsonText);
        // ["foot","張曉天",false,6.9,7,null]
  • Example 2-3- Encode a JSON array - Using List and streaming
       LinkedList list = new LinkedList();
        list.add("張曉天");
        list.add(100);
        list.add(1000.21);
        list.add(true);
        list.add(null);
        StringWriter out = new StringWriter();
        try {
            JSONValue.writeJSONString(list, out);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        String jsonText = out.toString();
        printJson(jsonText);
        // ["張曉天",100,1000.21,true,null]
  • Example 3 - Merge two JSON objects
       JSONObject json1 = new JSONObject();
        json1.put("name", "json1");
        json1.put("age", 3);
        json1.put("balance", 3.8);

        JSONObject json2 = new JSONObject();
        json2.put("is_vip", "是");
        json2.put("nickname", null);
        json2.put("num", 8.9);
        json2.putAll(json1); // 注意兩個對象的key不能一樣,否則會替換
        printJson(json2.toJSONString());
        // {"balance":3.8,"num":8.9,"nickname":null,"is_vip":"是","name":"json1","age":3}
  • Example 4 - Merge two JSON arrays
    JSONArray list1 = new JSONArray();
        list1.add("foo");
        list1.add(new Integer(100));
        list1.add(new Double(1000.21));

        JSONArray list2 = new JSONArray();
        list2.add(new Boolean(true));
        list2.add(null);

        JSONObject obj = new JSONObject();
        obj.put("name", "foo");
        obj.put("num", new Integer(100));
        obj.put("balance", new Double(1000.21));
        obj.put("is_vip", new Boolean(true));
        obj.put("nickname", null);

        obj.put("list1", list1);
        obj.put("list2", list2);
        printJson(obj.toJSONString());

        // {"balance":1000.21,"list2":[true,null],"num":100,"list1":["foo",100,1000.21],"nickname":null,"is_vip":true,"name":"foo"}
  • Example 5-1 - Combination of JSON primitives, Map and List
        Map m1 = new LinkedHashMap();
        Map m2 = new HashMap();
        List l1 = new LinkedList();

        m1.put("one", "第一值");
        m1.put("two", "第二個值");
        m2.put("k1", "m2-k1");
        m2.put("k2", "m2-k2");

        l1.add(m1);
        l1.add(m2);
        String json = JSONValue.toJSONString(l1);
        printJson(json);
        // [{"one":"第一值","two":"第二個值"},{"k1":"m2-k1","k2":"m2-k2"}]
  • Example 5-2 - Combination of JSON primitives, JSONObject, Map and List, and streaming
        StringWriter out = new StringWriter();
        JSONObject obj = new JSONObject();
        LinkedHashMap m1 = new LinkedHashMap();
        LinkedList l1 = new LinkedList();
        obj.put("k1", "v1");
        obj.put("k2", m1);
        obj.put("k3", l1);
        m1.put("mk1", "mv1");
        l1.add("lv1");
        l1.add("lv2");
        m1.put("mk2", l1);
        try {
            obj.writeJSONString(out);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("jsonString:");
        System.out.println(out.toString());
        String jsonString = obj.toJSONString();
        System.out.println(jsonString);
  • Example 6 - Customize JSON outputs
JSONArray users = new JSONArray();
        users.add(new User(123, "zxd", "zxd"));
        users.add(new User(124, "ksks", "ksk"));
        users.add(new User(125, "\"foo2\"", "secret2"));
        printJson(users.toJSONString());
        // [{userName:"zxd",ID:123},{userName:"ksks",ID:124},{userName:"\"foo2\"",ID:125}]
JSONArray users = new JSONArray();
        users.add(new User(123, "foo1", "secret1"));
        users.add(new User(124, "foo2", "secret2"));
        users.add(new User(125, "\"foo2\"", "secret2"));
        StringWriter out = new StringWriter();
        try {
            users.writeJSONString(out);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        printJson(out.toString());
        
        //[{userName:"foo1",ID:123},{userName:"foo2",ID:124},{userName:"\"foo2\"",ID:125}]
 
         
class User implements JSONAware {
    private int id;
    private String name;
    private String password;

    public User(int id, String name, String password) {
        this.id = id;
        this.name = name;
        this.password = password;
    }

    public String toJSONString() {
        StringBuffer sb = new StringBuffer();

        sb.append("{");

        sb.append(JSONObject.escape("userName"));
        sb.append(":");
        sb.append("\"" + JSONObject.escape(name) + "\"");

        sb.append(",");

        sb.append(JSONObject.escape("ID"));
        sb.append(":");
        sb.append(id);

        sb.append("}");
        // 也可以這樣寫
        /*
         * JSONObject obj = new JSONObject(); obj.put("userName", name);
         * obj.put("ID", new Integer(id)); return obj.toString();
         */
        return sb.toString();

    }

    public void writeJSONString(Writer out) throws IOException {
        LinkedHashMap obj = new LinkedHashMap();
        obj.put("userName", name);
        obj.put("ID", new Integer(id));
        JSONValue.writeJSONString(obj, out);
    }
}
 

如果你使用了maven來創建項目也可在pom中添加以下依賴:

<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1.1</version>

</dependency>

總結:jsonsimple對於簡單轉換成json對象,但是對於 比較復雜的對象就不太好了,復雜的對象都要實現JSONAware重寫對應的方法,才能實現指定格式的輸出。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM