Am trying to parse a huge JSON
array using Gson stream
where for every run, I just have to process 10 objects at a time.
So that on first run, it process 10. In second run, it starts from 11th. In third, it starts from 21st and so on... You get the drill.
JSON array is in the format:
[
{ "key1": "value1"},
{ "key2": "value2"},
{ "key3": "value3"},
{ "key4": "value4"},
..........
.........
..........
{ "key10": "value10"},
..........
.........
..........
{ "key20": "value20"},
..........
.........
..........
]
Am trying below code but seems like it doesn't work properly and am parsing always from the start only. This is what am doing:
public static void readJsonStream(int skipRows) {
JsonReader reader = null;
String FILENAME = "/examples/uh_data.json";
final InputStream stream = UHReportParser.class.getClass().getResourceAsStream(FILENAME);
try {
reader = new JsonReader(new InputStreamReader(stream, "UTF-8"));
Gson gson = new GsonBuilder().create();
// Read file in stream mode
reader.beginArray();
int count = 1;
while (reader.hasNext()) {
if (count++<=skipRows){
continue;
} else if(count>skipRows+10){
break;
}
else{
UserData data = null;
// Read data into object model
data = gson.fromJson(reader, UserData.class); //starts from one again
String description = data.getDescription();
}
}
} catch (UnsupportedEncodingException ex) {
ex.printStackTrace();
} catch (IOException ex) {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
What should be modified here? How can I achieve the desired results?
I didn't analyze your algorithm in depth, but it doesn't seem to skip values at the "skip" phase and I would definitely refactor your JSON stream reader in order to make it as clean as possible (at least for what I can do). This would allow you to reuse such a method as much as possible too. Consider the following methods:
Here is a JSON document I was using to test it (32 array elements in total):
Now, test it:
Example output:
As you can see, it's really easy.