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. Create project called JSONExample.
2. Create package called com.javatutorialscorner.gson
3. Create java class called GSONStreamWrite under com.javatutorialscorner.gson.
GSONStreamWrite.java
Now run the program see file written in specified location with following content.
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
- When it is impossible to load or undesirable to load the entire object model into memory.
- This is most relevant on mobile platform where memory is limited.
- When its necessary to read write a document before it is completely available.
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.javatutorialcorner.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.javatutorialcorner.com","Tutorials":["Java","Servlet","JSP","Struts","Hibernate","Spring"]}
0 comments:
Post a Comment