JsonParser In Java

Home / JsonParser In Java

In this article, we learn about How to parse JSON in java using JsonParser . JsonParser is used to parse the JsonObject and JsonArray.

As a java developer, we always deal with data in JSON or XML format. And sometimes we have to parse this data to perform some business logic.

And sometimes we have to convert the string into a JSON object or JSON array. So for this, we also use this JSON parser in java.

So in this example, we see how to convert a string into JsonObject and how to parse the JSON data using JsonParser.

To use this JsonParser in java application we have to add the below dependency in our pom.xml file.

<dependency>
    <groupId>com.googlecode.json-simple</groupId>
    <artifactId>json-simple</artifactId>
    <version>1.1.1</version>
</dependency>

Now Just take a programming example. In this example, we make a Post request and send some JSON data. And parse this JSON data using the parser.

Let’s take an example that we are trying to parse the below JsonObject.

{
	"name": "vasu",
	"age": 26,
	"email": "vasu@gmail.com"
}

So to parse the above JsonObject I will make the below logic in my controller class.

package com.javadream.jsonparser.controller;

import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class JsonParserController {

	private static final Logger logger = LoggerFactory.getLogger(JsonParserController.class);

	private JSONParser parser = new JSONParser();

	@PostMapping("/parseSimpleJson")
	public String parser(@RequestBody String payload) {
		try {
			logger.info("payload= " + payload);
			JSONObject jObj = (JSONObject) parser.parse(payload);
			String name = jObj.get("name").toString();
			String age = jObj.get("age").toString();
			String email = jObj.get("email").toString();
			
			logger.info("name= "+name + " ,age= "+age + " ,email= "+email);
			return "Your name is "+ name + " and you are " + age + " old. Your email id is" + email ;
 		} catch (Exception e) {
			logger.error(e.getMessage());
			return "Parse Error Try Again";
		}
	}
}

We are using below steps to parse this jsonObject.

  1. We are creating a JSONParser object.
  2. Then receive this JsonObject in String formate in our Post endPoint.
  3. Convert this String payload to JSON object using the parser.
  4. Now we get a JsonObject.
  5. Now we get the object value using a key.

Now Run this application and make a post request with the given data from the postman.

jsonparser

Now take a complex JsonObject example and try to parse that. Suppose I am getting below JsonObject.

{
	"name": "vasu",
	"age": 26,
	"email": "vasu@gmail.com",
	"educationDetail": {
		"college": "GEHU Dehradun",
		"course": "B.Tech",
		"Branch": "CSE"
	}
}

Now we have another JsonObject with the name educationDetail in our main JsoObject. Let’s see how to parse this data.

So to parse this I am creating another post endPoint. See the code to parse this complex object.

	@PostMapping("/parserComplexJson")
	public String parserComplexJson(@RequestBody String payload) {
		try {
			logger.info("payload= " + payload);
			JSONObject jObj = (JSONObject) parser.parse(payload);
			String name = jObj.get("name").toString();
			String age = jObj.get("age").toString();
			String email = jObj.get("email").toString();

			JSONObject educationObj = (JSONObject) jObj.get("educationDetail");
			String collegeName = educationObj.get("college").toString();
			String course = educationObj.get("course").toString();
			String branch = educationObj.get("Branch").toString();

			return "Hi " + name + " you are student of "+ collegeName +" college and your course is "+ course; 
		} catch (Exception e) {
			logger.error(e.getMessage());
			return "Parse Error Try Again";
		}
	}

Now run this application and make a post request with given JsonObject.

jsonparser java

Now take an example of a hard JsonObject where we have a JsonArray inside our main JsonObject.

{
	"name": "vasu",
	"age": 26,
	"email": "vasu@gmail.com",
	"educationDetail": {
		"college": "GEHU Dehradun",
		"course": "B.Tech",
		"Branch": "CSE"
	},
	"matrixEducation": [{
		"10ClassBoard": "Pass 10 class from UP Board"
	}, {
		"12ClassBoard": "pass 12 class from UP Board"
	}]
}

Now try to parse the above JsonObject. For this, I am creating another post endPoint. Look at the code below.

	@PostMapping("/parserHardJson")
	public String parserHardJson(@RequestBody String payload) {
		try {
			logger.info("payload= " + payload);
			JSONObject jObj = (JSONObject) parser.parse(payload);
			String name = jObj.get("name").toString();
			String age = jObj.get("age").toString();
			String email = jObj.get("email").toString();

			JSONObject educationObj = (JSONObject) jObj.get("educationDetail");
			String collegeName = educationObj.get("college").toString();
			String course = educationObj.get("course").toString();
			String branch = educationObj.get("Branch").toString();

			JSONArray matrixDetail = (JSONArray) jObj.get("matrixEducation");
			
			JSONObject highSchoolObj = (JSONObject)matrixDetail.get(0);
			String highSchoolboard = highSchoolObj.get("10ClassBoard").toString();
			
			JSONObject interSchoolObj = (JSONObject)matrixDetail.get(1);
			String interSchoolboard = interSchoolObj.get("12ClassBoard").toString();
			

			return "Hi " + name + " you 10 board is  " + highSchoolboard + " and for 12 is  " + interSchoolboard;
		} catch (Exception e) {
			logger.error(e.getMessage());
			return "Parse Error Try Again";
		}
	}

Now if you see JsonArray is the same as a simple Array. It also stores data at indexes. So here I have two indexes first index store information for 10ClassBoard. and second, store information for 12ClassBoard.

Now your class look like below with all three methods.

package com.javadream.jsonparser.controller;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class JsonParserController {

	private static final Logger logger = LoggerFactory.getLogger(JsonParserController.class);

	private JSONParser parser = new JSONParser();

	@PostMapping("/parseSimpleJson")
	public String parser(@RequestBody String payload) {
		try {
			logger.info("payload= " + payload);
			JSONObject jObj = (JSONObject) parser.parse(payload);
			String name = jObj.get("name").toString();
			String age = jObj.get("age").toString();
			String email = jObj.get("email").toString();

			logger.info("name= " + name + " ,age= " + age + " ,email= " + email);
			return "Your name is " + name + " and you are " + age + " old. Your email id is" + email;
		} catch (Exception e) {
			logger.error(e.getMessage());
			return "Parse Error Try Again";
		}
	}

	@PostMapping("/parserComplexJson")
	public String parserComplexJson(@RequestBody String payload) {
		try {
			logger.info("payload= " + payload);
			JSONObject jObj = (JSONObject) parser.parse(payload);
			String name = jObj.get("name").toString();
			String age = jObj.get("age").toString();
			String email = jObj.get("email").toString();

			JSONObject educationObj = (JSONObject) jObj.get("educationDetail");
			String collegeName = educationObj.get("college").toString();
			String course = educationObj.get("course").toString();
			String branch = educationObj.get("Branch").toString();

			return "Hi " + name + " you are student of " + collegeName + " college and your course is " + course;
		} catch (Exception e) {
			logger.error(e.getMessage());
			return "Parse Error Try Again";
		}
	}

	@PostMapping("/parserHardJson")
	public String parserHardJson(@RequestBody String payload) {
		try {
			logger.info("payload= " + payload);
			JSONObject jObj = (JSONObject) parser.parse(payload);
			String name = jObj.get("name").toString();
			String age = jObj.get("age").toString();
			String email = jObj.get("email").toString();

			JSONObject educationObj = (JSONObject) jObj.get("educationDetail");
			String collegeName = educationObj.get("college").toString();
			String course = educationObj.get("course").toString();
			String branch = educationObj.get("Branch").toString();

			JSONArray matrixDetail = (JSONArray) jObj.get("matrixEducation");
			
			JSONObject highSchoolObj = (JSONObject)matrixDetail.get(0);
			String highSchoolboard = highSchoolObj.get("10ClassBoard").toString();
			
			JSONObject interSchoolObj = (JSONObject)matrixDetail.get(1);
			String interSchoolboard = interSchoolObj.get("12ClassBoard").toString();
			

			return "Hi " + name + " you 10 board is  " + highSchoolboard + " and for 12 is  " + interSchoolboard;
		} catch (Exception e) {
			logger.error(e.getMessage());
			return "Parse Error Try Again";
		}
	}
}

Now run your application and make a post request with this hard JsonObject data.

jsonparser

Complete Code on Github: JsonParser Example

You may also like:

Spring boot security using JWT ( JSON WEB TOKENS ).

spring batch example

Spring boot cache example

Actuator in spring boot for monitoring application

Profiles in Spring boot application

Help Others, Please Share

About Author

15 Comments
  1. self hypnosis course

    What’s Happening i am new to this, I stumbled upon this I’ve found It
    positively useful and it has helped me out loads. I hope to give a contribution & assist other users like its
    aided me. Good job.

  2. sikis izle

    Nice post. I learn something totally new and challenging on blogs I stumbleupon every day. Clementine Alaster Onida

  3. erotik

    Very informative blog article. Thanks Again. Much obliged. Cicely Burch Adnopoz

  4. erotik izle

    I have been checking out some of your posts and i must say clever stuff. I will surely bookmark your site. Augusta Gail Stultz

  5. erotik izle

    Hi there to all, how is all, I think every one is getting more from this site, and your views are fastidious designed for new people. Lilia Maury Moia

  6. sikis izle

    A big thank you for your post. Thanks Again. Keep writing. Bennie Barbabas Gratiana

  7. erotik izle

    Very good write-up. I definitely appreciate this website. Camel Brew Bazil

  8. erotik

    This site really has all the information and facts I needed about this subject and didn at know who to ask. Mindy Ezekiel Griffy

  9. sikis izle

    Just wanna tell that this is very beneficial , Thanks for taking your time to write this. Roda Adam Abner

  10. sikis izle

    Way cool! Some very valid points! I appreciate you writing this article and also the rest of the site is also really good. Teddy Micheal Bradley

  11. film

    If some one wishes expert view on the topic of running a blog then i propose him/her to pay a visit this webpage, Keep up the fastidious job. Carlye Stavro Maurits

  12. film

    Helpful info. Lucky me I discovered your website by accident, and I am stunned why this coincidence did not came about in advance! I bookmarked it. Lucie Tedd Eustis

  13. film

    I wrote down your blog in my bookmark. I hope that it somehow did not fall and continues to be a great place for reading texts. Guenna Devland Rolandson

Leave a Reply

Your email address will not be published. Required fields are marked *