Home > Java > javaTutorial > How do we decode a JSON object in Java?

How do we decode a JSON object in Java?

WBOY
Release: 2023-08-27 08:33:11
forward
1014 people have browsed it

How do we decode a JSON object in Java?

#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.

Example

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);
      }
   }
}
Copy after login

Output

2nd Array element:
{"1":{"2":{"3":{"4":[5,{"6":{"7":8}}]}}}}

Field "1"
{"2":{"3":{"4":[5,{"6":{"7":8}}]}}}
{}
[6]
[6,3]
Copy after login

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!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template