Parsing JSON Output using JAVA

 

Use the JSONParser methods to parse a response that’s returned from a call to an external service that is in JSON format, such as a JSON-encoded response of a Web service callout.


Here is the code to parse the JSON string using JAVA:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

public class JsonParser {
 
 public static void main(String args[]) throws ParseException{
  
  String Response = "{\"Profile\":{\"Name\":\"Sarthak\", \"Age\":\"23\"," + "\"Address\":\"Lucknow\"} }";

  JSONParser parser = new JSONParser();
  Object obj = parser.parse(Response);

  JSONObject jsonObject = (JSONObject) obj;
  JSONObject jsonObject1 = (JSONObject) jsonObject.get("Profile");
  String name = (String) jsonObject1.get("Name");
  Long age = new Long((String) jsonObject1.get("Age"));
  String address = (String) jsonObject1.get("Address");
  System.out.println(name);
  System.out.println(age);
  System.out.println(address);

 }

}

Output:

Sarthak

23

Lucknow


Download the JAR here

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s