Showing posts with label json.how to read json in java. Show all posts
Showing posts with label json.how to read json in java. Show all posts

Friday, 13 February 2015

How To Read JSON In Java (Set 3)

user.json

{"employees":[
    {"firstName":"Rahul", "lastName":"Dhiman"},
    {"firstName":"Anna", "lastName":"Smith"},
    {"firstName":"MS", "lastName":"Dhoni"}
]}


TestJson.java

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 TestJsonset1 {
    public static void main(String[] args) {
         String filePath = "D:\\json\\user.json";
        try {
            FileReader reader = new FileReader(filePath);
            JSONParser jsonParser = new JSONParser();
            JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);
            JSONArray lang= (JSONArray) jsonObject.get("employees");
             Iterator i=lang.iterator();
             while (i.hasNext()) {
                 JSONObject jsonobject1=(JSONObject)i.next();
                System.out.println("first name="+jsonobject1.get("firstName")+"   last name="+jsonobject1.get("lastName"));  
            }
        }catch (Exception e) {
                System.out.println(e);
            }
        }
}

Output:

first name=Rahul   last name=Dhiman
first name=Anna   last name=Smith
first name=MS   last name=Dhoni