728x90 AdSpace

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.
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(
   jsonWriter.name("Name").value("Java Tutorials Corner");

  } 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.javatutorialcorner.com","Tutorials":["Java","Servlet","JSP","Struts","Hibernate","Spring"]}
Annamalai Thangaraj

Annamalai is working as Technical Lead in Leading Telecom company with 5+ years experience in Identity and Access Management , Telecom and Networks, BigData, Java, Spring, Struts, Hibernate, AngularJS, and Enterprise Web Application Development.

Website: Java Tutorials Corner

Shop and help us

Flipkart Offer Snapdeal offer Amazon.in offer Amazon.com offer
  • Blogger Comments
  • Facebook Comments
  • Disqus Comments


Post a Comment

Item Reviewed: Write JSON using GSON Streaming Rating: 5 Reviewed By: Annamalai Thangaraj