728x90 AdSpace

Sunday, 6 October 2013

Read JSON using GSON Stream


In this tutorial we are going to see how to read JSON Data from file using GSON
1. Create project called JSONExample.
2. Create package called com.javatutorialscorner.gson 
3. Create java class called GSONStreamRead under com.javatutorialscorner.gson.
GSONStreamRead.java
package com.javatutorialscorner.gson;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

import com.google.gson.stream.JsonReader;

public class GSONStreamRead {

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

  try {
   jsonReader = new JsonReader(new FileReader(
     "C:\\jtc\\javatutorialscorner.json"));
   jsonReader.beginObject();
   while (jsonReader.hasNext()) {
    String name = jsonReader.nextName();

    if (name.equals("Name")) {
     System.out.println("String : " + jsonReader.nextString());
    } else if (name.equals("URL")) {
     System.out.println("String : " + jsonReader.nextString());
    } else if (name.equals("Tutorials")) {

     jsonReader.beginArray();
     while (jsonReader.hasNext()) {
      System.out.println("Arary List : "
        + jsonReader.nextString());
     }
     jsonReader.endArray();
    } else {
     jsonReader.skipValue();
    }

   }
  } catch (FileNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }

 }

}

Now run the program see the following output in console.

String : Java Tutorials Corner

String : http://www.javatutorialcorner.com


Arary List : Java


Arary List : Servlet


Arary List : JSP


Arary List : Struts


Arary List : Hibernate


Arary List : Spring
Annamalai Thangaraj

Annamalai is a Sr.Software Engineer with 3+ years experience in Java, Spring, Struts, Hibernate, IDM/IAM, and Enterprise Web Application Development.

Website: Java Tutorials Corner

  • Blogger Comments
  • Facebook Comments
  • Disqus Comments

0 comments:

Post a Comment

Item Reviewed: Read JSON using GSON Stream Rating: 5 Reviewed By: Annamalai Thangaraj