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?
4 Answers
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:
Comments
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
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
flowerProgrammer
I get the execption: java.lang.ClassCastException: org.json.simple.JSONArray cannot be cast to org.json.simple.JSONObject
Krishan
that means you have to directly cast it to JsonArray. JSONArray json = (JSONArray) parser.parse(fileReader);
JsonNodeor you use the streaming API.