Sunday, 6 October 2013

Write JSON using GSON Streaming



Gson can read and write JSON as an object model or stream.Gson’s object model uses the same approach as XML DOM and XML pull parser.Gson doesn’t support event-based model like SAX.
Streaming Access
JsonReader and JsonWriter class provides Streaming access to JSON document which were added in GSON 1.6. These classes operate on a JSON document as sequence of tokens that are traversed in depth-first order. Because the streams operate on one token at a time.
Most application uses Object model API. JSON Streaming is useful in following cases
  1. When it is impossible to load or undesirable to load the entire object model into memory.
  2. This is most relevant on mobile platform where memory is limited.
  3. When its necessary to read write a document before it is completely available.
Gson also support Mixed Streaming and Object model acces.We will see the mixed model in upcoming chapter now see  JsonWriter  to write JSON data into file.
1. Create project called JSONExample.
2. Create package called com.javatutorialscorner.gson 
3. Create java class called GSONStreamWrite under com.javatutorialscorner.gson.
GSONStreamWrite.java
package com.javatutorialscorner.gson;

import java.io.FileWriter;
import java.io.IOException;

import com.google.gson.stream.JsonWriter;

public class GSONStreamWrite {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

JsonWriter jsonWriter = null;
try {
jsonWriter = new JsonWriter(new FileWriter(
"C:\\jtc\\javatutorialscorner.json"));
jsonWriter.beginObject();
jsonWriter.name("Name").value("Java Tutorials Corner");
jsonWriter.name("URL").value("http://www.javatutorialscorner.com");
jsonWriter.name("Tutorials");
jsonWriter.beginArray();
jsonWriter.value("Java");
jsonWriter.value("Servlet");
jsonWriter.value("JSP");
jsonWriter.value("Struts");
jsonWriter.value("Hibernate");
jsonWriter.value("Spring");

jsonWriter.endArray();
jsonWriter.endObject();
jsonWriter.close();
} catch (IOException e) {
// TODO: handle exception
}
}

}

Now run the program see file written in specified location with following content.

{"Name":"Java Tutorials Corner","URL":"http://www.javatutorialscorner.com","Tutorials":["Java","Servlet","JSP","Struts","Hibernate","Spring"]}

0 comments

Post a Comment