1

I have a wikidata json file, and I want to read it into a JSONArray so that I could iterate over its items and get each element's properties and values. How can I do it? I tried iterating over the whole text and parsing each line, but it is too long and complicated for a large file, and I can't get It right that way. Is there more efficient way in Java for reading a JSON file into a JSON array or object so that I could iterate over its items?

2
  • 1
    You can use Jackson; depending on how large it is, you read it as a JsonNode or you use the streaming API. Commented Nov 18, 2015 at 11:12
  • Search about GSON, for example. github.com/google/gson Commented Nov 18, 2015 at 11:13

4 Answers 4

3

You can read a huge json file with Gson streaming:

JsonReader reader = new JsonReader(new InputStreamReader(inputStream, "UTF-8"));
reader.beginArray();
while (reader.hasNext()) {
      // Message message = Gson.fromJson(reader, Message.class);
      // ...
}
reader.endArray();
reader.close();

Ref:

  1. Gson streaming
  2. Gson Streaming to read and write JSON
Sign up to request clarification or add additional context in comments.

Comments

1

I suggest using https://github.com/jayway/JsonPath to parse it and query the different parts you need. It will construct the list for you.

ie. $.store.book[?(@.price < 10)]

Comments

0

A good solution is to use a library for this job. Very good library is the gson . You can read the documentation of the library here.

Comments

0
FileReader fileReader = new FileReader(file); 
JSONObject json = (JSONObject) parser.parse(fileReader);
String name = (String) json.get("name"); 
JSONArray departments = (JSONArray) json.get("departments");

I think this might help

2 Comments

I get the execption: java.lang.ClassCastException: org.json.simple.JSONArray cannot be cast to org.json.simple.JSONObject
that means you have to directly cast it to JsonArray. JSONArray json = (JSONArray) parser.parse(fileReader);

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.