📜  JSON.simple-使用JSONValue

📅  最后修改于: 2020-11-16 07:16:14             🧑  作者: Mango


JSONValue提供一个静态方法parse()来解析给定的json字符串,以返回一个JSONObject,然后该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]