Gson Streaming API Mixing With Object Model
In the previous example we talked about the core GSON Streaming API. This example we’ll mix GSON Streaming API together with GSON Object Model. This leaves us with the benefit of not loading the entire JSON document in memory but small portions of the document and it’s very concise since it uses GSON Object Model.
For a simple example, we are writing this object into a file and then read it back.
package com.memorynotfound.json;
import java.util.List;
public class Car {
private String name;
private String model;
private int year;
private List colors;
public Car(String name, String model, int year, List colors) {
this.name = name;
this.model = model;
this.year = year;
this.colors = colors;
}
@Override
public String toString() {
return "Car{" +
"name='" + name + '\'' +
", model='" + model + '\'' +
", year=" + year +
", colors=" + colors +
'}';
}
}
Writing JSON with JsonWriter
We’ll create the JSON document using the JsonWriter
. We can simply create an instance of the Car
class and write the object to a file using GSON toJson()
method.
package com.memorynotfound.json;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.stream.JsonWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Arrays;
public class GsonStreamWriter {
public static void main(String... args){
Gson gson = new GsonBuilder().create();
JsonWriter writer;
try {
writer = new JsonWriter(new FileWriter("result.json"));
Car car = new Car("BMW", "X1", 2016, Arrays.asList("BLUE", "RED", "WHITE"));
gson.toJson(car, Car.class, writer);
writer.close();
} catch (IOException e) {
System.err.print(e.getMessage());
}
}
}
The previous code generates the following JSON document.
{"name":"BMW","model":"X1","year":2016,"colors":["BLUE","RED","WHITE"]}
Reading JSON with JsonReader
This code reads a JSON document containing a Car
instance. It reads a stream to avoid loading the complete document into memory. It is concise because it uses Gson’s object-model to parse the individual car.
package com.memorynotfound.json;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.stream.JsonReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class GsonStreamReader {
public static void main(String... args){
Gson gson = new GsonBuilder().create();
JsonReader reader;
try {
reader = new JsonReader(new FileReader("result.json"));
Car car = gson.fromJson(reader, Car.class);
System.out.println(car);
reader.close();
} catch (FileNotFoundException e) {
System.err.print(e.getMessage());
} catch (IOException e) {
System.err.print(e.getMessage());
}
}
}
The previous code generates the following output.
Car{name='BMW', model='X1', year=2016, colors=[BLUE, RED, WHITE]}