share

Friday, 13 February 2015

How To Read JSON In Java (Set 1)



user.json

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

TestJson.java

import java.io.FileReader;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

public class TestJson{
    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);
            System.out.println(jsonObject);
        }catch (Exception e) {
                System.out.println(e);
            }
        }
}



Output:

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

No comments:

Post a Comment