I have a very large JSON file in the following format:
[{\"fullname\": \"name1\", \"id\": \"123\"}, {\"fullname\": \"name2\", \"id\": \"245\"}, {\"fullname\": \
you can use Json.simple java api , below is code that can helpful to you
byte[] bFile = Files.readAllBytes(new File("C:/xyz.json").toPath());
JSONArray root = (JSONArray) JSONValue.parseWithException(bFile);
JSONObject rootObj = (JSONObject) root.get(0);
You can get values from JSONObject based on key , it also depends on format of your json as there could be nested json data. So you have to extract data accordingly . Apart from this you can use jackson parser api or GSON as well.
Make your life easy and use an ObjectMapper
.
This way you simply define a Pojo with the same properties as you json object.
In you case you need a Pojo that looks like this:
public class Person{
private String fullname;
private int id;
public Person(String fullname, int id) {
this.fullname = fullname;
this.id = id;
}
public String getFullname() {
return fullname;
}
public int getId() {
return id;
}
}
With that you only need to do:
ObjectMapper objectMapper = new ObjectMapper();
List<Person> persons = objectMapper.readValue(myInputStream, TypeFactory.defaultInstance().constructCollectionType(List.class, Person.class));
This is a hassle free and type safe approach.
Dependencies needed:
https://github.com/FasterXML/jackson-databind
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
Okay folks...just solved my problem. I am posting the solution in case someone runs into the same issue again, can use my solution. My solution is partly motivated by Rahul Rabhadiya. Thanks, dude.
try{
row=br.readLine();
JSONArray root = (JSONArray) JSONValue.parseWithException(row);
for (int i=0;i<root.size();i++)
{
JSONObject rootObj = (JSONObject) root.get(i);
String fullname=(String) rootObj.get("fullname");
System.out.println (fullname);
}
}catch(Exception e)
{
e.printStackTrace();
}
I would suggest going with Jackson, in particular the Jackson Streaming API which is perfect for parsing large arrays like this.
See this answer: https://stackoverflow.com/a/24838392/3765428
Your json is a JSONArray, so when you are parsing it, you need to parse it as a JSONArray.
JSONParser jsonParser = new JSONParser();
JSONArray a = (JSONArray) jsonParser.parse(new FileReader(src));
for (Object o : a) {
// access your object here.
}