CodesJava

Easy learning with example program codes

How to parse json in java with example?


Let us discuss how to parse JSON objects using Java with the help of below example.

Steps:

1. Include JSON jar in classpath.
2. Define JSON string.
3. Create JSON parser object
4. Parse JSON string using JSON parser.
5. Process the object.

Example:

JSONTest.java

package com.codesjava.business;
 
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
 
/**
 * This class is used to parse the JSON string.
 * @author codesjava
 */
public class JSONTest {
    public static void main(String args[]) {
	  // JSON String
	  String jsonString = "[{\"name\":\"Swati\",\"rollNo\":" +
		"\"MCA/07/01\",\"id\":10},{\"name\":\"Prabhjot\",\"" +
		"rollNo\":\"MCA/07/39\",\"id\":50}]";
 
	  // Create JSON parser object.
	  JSONParser parser = new JSONParser();
	  try {
		// Parse JSON string using JSON parser.
		Object object = parser.parse(jsonString);
		JSONArray array = (JSONArray) object;
		System.out.println("First object:");
		System.out.println(array.get(0));
 
		// Get JSON object from JSON array.
		JSONObject jsonObject = (JSONObject) array.get(1);
		System.out.println("Second object:");
		System.out.println("Name:" + jsonObject.get("name"));
	  } catch (ParseException e) {
		e.printStackTrace();
	  }
    }
}

Output:

First object:
{"id":10,"rollNo":"MCA\/07\/01","name":"Swati"}
Second object:
Name:Prabhjot

Download this example.
 
Previous Topic: How to use JSON object in java?

Related Topics:

How to build java project using ant in eclipse?
JAXB marshalling – convert java object to xml example.
How to create pdf file in java using iText jar?
Generics class example.
OGNL in struts 2.
Hibernate One-to-One Mapping using xml.
Send inline image in email using JavaMail API.
Quartz 2 JobListener example.

 

Sign Up/ Sign In
Ask a Question


Industrial Training

We offers Placement Oriented Training on Java, Spring, JSF, Hibernate, PHP, AngularJS, Angular 4, PLSQL, Oracle BI Publisher etc. We also provides Online training, please mail us at hr@codesjava.com.

Development

We also provides the Development services for Website Development , Java Development, PHP Development, Android App Development etc. You can contact us on hr@codesjava.com.

Copyright © 2018 CodesJava DMCA.com Protection Status SiteMap Reference: Java Wiki