forked from nsquare-jdzone/java-examples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJsonStreamingGsonExample.java
More file actions
49 lines (40 loc) · 1.72 KB
/
JsonStreamingGsonExample.java
File metadata and controls
49 lines (40 loc) · 1.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package com.javadeveloperzone;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.stream.JsonReader;
import java.io.*;
import java.nio.charset.StandardCharsets;
public class JsonStreamingGsonExample {
public static void main(String[] args) {
long start = System.currentTimeMillis();
JsonStreamingGsonExample jsonStreamingGsonExample = new JsonStreamingGsonExample();
String jsonFilePath = "H:\\Work\\Data\\sample.json";
jsonStreamingGsonExample.parse(jsonFilePath);
System.out.println("Total Time Taken : "+(System.currentTimeMillis() - start)/1000 + " secs");
}
public void parse(String jsonFilePath){
//create JsonReader object and pass it the json file,json source or json text.
try(JsonReader jsonReader = new JsonReader(
new InputStreamReader(
new FileInputStream(jsonFilePath), StandardCharsets.UTF_8))) {
Gson gson = new GsonBuilder().create();
jsonReader.beginArray(); //start of json array
int numberOfRecords = 0;
while (jsonReader.hasNext()){ //next json array element
Document document = gson.fromJson(jsonReader, Document.class);
//do something real
// System.out.println(document);
numberOfRecords++;
}
jsonReader.endArray();
System.out.println("Total Records Found : "+numberOfRecords);
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}