Reading JSON using json.simple.JSONObject in java

Maven dependency -


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



If you are beginner don't worry learn how to Create new Maven project - In 2 minutes

c:/Ankit/myJson.json >

{
"empId" : 11,
"address" : [ "Paris", "London" ],
"birthDate" : 1534577772673,
"emp_name" : "ankit"
}


Reading JSON using json.simple.JSONObject in java 

package com.ankit.json;

import java.io.FileReader;
import java.util.Iterator;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

public class jsonReadExample {
    public static void main(String[] args) {
          JSONParser parsernew JSONParser();

          try {

                 Object objparser.parse(new FileReader("c:/Ankit/myJson.json"));
                 JSONObject jsonObject = (JSONObject) obj;
                 System.out.println("jsonObject = "jsonObject);

                 System.out.println("empId = "+(Long) jsonObject.get("empId"));

                 System.out.println("empNAme = "+(String) jsonObject.get("emp_name"));

                 System.out.println("address= ");
                 // JSONArray
                 JSONArray list = (JSONArray) jsonObject.get("address");

                 Iterator<String> iteratorlist.iterator();
                 while (iterator.hasNext()) {
                       System.out.println(iterator.next());
                 }

          catch (Exception e) {
                 e.printStackTrace();
          }

    }
}

// Output
/*
jsonObject = {"empId":11,"address":["Paris","London"],"emp_name":"ankit","birthDate":1534577772673}
empId = 11
empNAme = ankit
address=
Paris
London
*/


Related links >

1. Jackson JSON -

We can use Jackson api for for processing JSON in java.

Jackson JSON examples


2. Java provides API (JSR 353) for Processing  JSON (JSR 353).
It provides -
  • Object Model API
  • Streaming API

Java API for JSON processing examples >



3. Simple  (simple.JSONObject)



4. Google Gson - processing java json


eEdit
Must read for you :