JSON.simple - 使用 JSONValue



JSONValue 提供一個靜態方法 parse() 來對給定 JSON 字串進行解析,以返回一個 JSONObject,然後可以使用它來獲取解析的值。請看下面的示例。

示例

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;

public class JsonDemo {
   public static void main(String[] args) {
      String s = "[0,{\"1\":{\"2\":{\"3\":{\"4\":[5,{\"6\":7}]}}}}]";
      Object obj = JSONValue.parse(s);
      JSONArray array = (JSONArray)obj;

      System.out.println("The 2nd element of array");
      System.out.println(array.get(1));
      System.out.println();

      JSONObject obj2 = (JSONObject)array.get(1);
      System.out.println("Field \"1\"");
      System.out.println(obj2.get("1"));    

      s = "{}";
      obj = JSONValue.parse(s);
      System.out.println(obj);

      s = "[5,]";
      obj = JSONValue.parse(s);
      System.out.println(obj);

      s = "[5,,2]";
      obj = JSONValue.parse(s);
      System.out.println(obj);
   }
}

輸出

The 2nd element of array
{"1":{"2":{"3":{"4":[5,{"6":7}]}}}}

Field "1"
{"2":{"3":{"4":[5,{"6":7}]}}}
{}
[5]
[5,2]
廣告