#JSON is a lightweight, text-based and language-independent data exchange format. JSON can represent two structured types such as objects and arrays. We can decode JSON objects using JSONObject and JSONArray from json.simple API. JSONObject works as java.util.Map and JSONArray works as java.util.List.
In the example below, we can decode a JSON object.
import org.json.simple.*; import org.json.simple.parser.*; public class JSONDecodingTest { public static void main(String[] args) { JSONParser parser = new JSONParser(); String str = "[ 0 , {\"1\" : { \"2\" : {\"3\" : {\"4\" : [5, { \"6\" : { \"7\" : 8 } } ] } } } } ]"; try { Object obj = parser.parse(str); JSONArray array = (JSONArray)obj; System.out.println("2nd Array element: "); System.out.println(array.get(1)); System.out.println(); JSONObject object2 = (JSONObject) array.get(1); System.out.println("Field \"1\""); System.out.println(object2.get("1")); str = "{}"; obj = parser.parse(str); System.out.println(obj); str = "[6,]"; obj = parser.parse(str); System.out.println(obj); str = "[6,,3]"; obj = parser.parse(str); System.out.println(obj); } catch(ParseException parseExp) { System.out.println("Exception position: " + parseExp.getPosition()); System.out.println(parseExp); } } }
2nd Array element: {"1":{"2":{"3":{"4":[5,{"6":{"7":8}}]}}}} Field "1" {"2":{"3":{"4":[5,{"6":{"7":8}}]}}} {} [6] [6,3]
The above is the detailed content of How do we decode a JSON object in Java?. For more information, please follow other related articles on the PHP Chinese website!