How To Read JSON In Java (Set 2)

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.JSONArray;
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);
JSONArray lang= (JSONArray) jsonObject.get(“employees”);
for (int i = 0; i < lang.size(); i++) {
System.out.println(lang.get(i));
}
}catch (Exception e) {
System.out.println(e);
}
}
}

Output:
{“firstName”:”Rahul”,”lastName”:”Dhiman”}
{“firstName”:”Anna”,”lastName”:”Smith”}
{“firstName”:”MS”,”lastName”:”Dhoni”}

Leave a Reply

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

45 − = 41