1

I have a very large JSON file in the following format:

[{"fullname": "name1", "id": "123"}, {"fullname": "name2", "id": "245"}, {"fullname": "name3", "id": "256"}]

It looks like a JSONArray. All the records are written in the same line.

Can you help me how can I parse this file using Java. I want to read each JSON object and display all the fullname and ids. Below is my attempt, but my code is not working:

import org.apache.commons.lang3.StringEscapeUtils;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

public class JSONFileReaderDriver {

public static void main(String[] args) throws FileNotFoundException, 
IOException, ParseException 
{
 String filename="Aarau";
 String src="C:\\"+filename+".json";
 JSONParser parser = new JSONParser();
 JSONObject obj;
 try
    {
        BufferedReader br=new BufferedReader (new FileReader(src));  
        obj = (JSONObject) new JSONParser().parse(row);
        String fullname=obj.get("fullname");
        String id=obj.get("id");
        System.out.println ("fullname: "+fullname+" id: "+id);
    }catch(Exception e)
     {e.printStackTrace();}
   br.close();
  }
 }
5
  • 2
    Do you plan to use any library like gson if that's easy way to parse? Commented Nov 22, 2017 at 13:44
  • In what way is your code not working? Do you see any errors? Commented Nov 22, 2017 at 13:45
  • "but my code is not working" - What specifically is not working? Are there any errors or exceptions? Commented Nov 22, 2017 at 13:45
  • Error: Unexpected token END OF FILE at position 0. at org.json.simple.parser.JSONParser.parse(JSONParser.java:257) at org.json.simple.parser.JSONParser.parse(JSONParser.java:81) at org.json.simple.parser.JSONParser.parse(JSONParser.java:75) at JSONReader.JSONFileReaderDriver.main(JSONFileReaderDriver.java:56) Commented Nov 22, 2017 at 13:54
  • [...].parse(row); - What is row? Commented Nov 22, 2017 at 14:06

5 Answers 5

5

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>
Sign up to request clarification or add additional context in comments.

Comments

4

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.

Comments

3

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();
        }

1 Comment

You should have given the answer credit to Rahul Rabhadiya because he came up with this solution just before you did.
3

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. 
        }

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.