Gson JsonReader and JsonWriter example
Gson provides APIs to read and write JSON as an object model or stream. The GSON JsonReader & JsonWriter use streaming model to process JSON.
To use Gson JsonReader & JsonWriter, you need to download gson-2.8.5.jar from gson-2.8.5.jar
1) JsonReader example
import java.io.IOException; import java.io.StringReader; import com.google.gson.stream.JsonReader; public class TestGsonJsonReader { public static void main(String[] args) { String jsonString = "{\"id\":12345, \"name\":\"Jason Bourne\", \"age\":35, " + "\"roles\":[\"Actor\",\"Father\"]}"; JsonReader jsonReader = new JsonReader(new StringReader(jsonString)); try { jsonReader.beginObject(); while(jsonReader.hasNext()){ String key = jsonReader.nextName(); if ("id".equals(key)){ System.out.println(jsonReader.nextInt()); } else if("name".equals(key)){ System.out.println(jsonReader.nextString()); } else if("age".equals(key)){ System.out.println(jsonReader.nextInt()); } else if("roles".equals(key)){ jsonReader.beginArray(); while (jsonReader.hasNext()) { System.out.println(jsonReader.nextString()); } jsonReader.endArray(); } else { jsonReader.skipValue(); } } jsonReader.endObject(); } catch (IOException e) { e.printStackTrace(); } } }
Output :
12345 Jason Bourne 35 Actor Father
2) JsonWriter example
import java.io.FileWriter; import java.io.IOException; import com.google.gson.stream.JsonWriter; public class TestGsonJsonWriter { public static void main(String[] args) { try (JsonWriter writer = new JsonWriter(new FileWriter("C:\\actor.json"))) { writer.beginObject(); writer.name("id").value(12345); writer.name("name").value("Jason Bourne"); writer.name("age").value(35); writer.name("roles"); writer.beginArray(); writer.value("Actor"); writer.value("Father"); writer.endArray(); writer.endObject(); } catch (IOException e) { e.printStackTrace(); } } }
Output actor.json:
{"id":12345,"name":"Jason Bourne","age":35,"roles":["Actor","Father"]}
References :
Gson streaming
JsonReader
JsonWriter