JavaBeat

  • Home
  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)
  • Privacy

Creating JSON document using Java and GSON API

May 5, 2012 by Mohamed Sanaulla Leave a Comment

We saw how to parse JSON using GSON API, in this post we would take a look at how the same GSON API can be used to create JSON from the Java objects. Please read this to get an idea of what GSON is. Diving right into the topic of this example, we would make use of the toJson method of com.google.gson.Gson class. One of the overloaded versions of toJson() takes in an source of type Object and the type information which is of class java.lang.reflect.Type.

also read:

  • JSON Tutorials
  • Java EE Tutorials
  • Design Patterns Tutorials
  • Java File IO Tutorials

Lets define the model which would hold the data:

[code lang=”java”]
class Book{

@SerializedName("isbn")
String isbn;

@SerializedName("title")
String title;

@SerializedName("publication")
String publication;

@SerializedName("authors")
String authors;

public Book ( String isbn,
String title,
String publication,
String authors)
{
this.isbn = isbn;
this.title = title;
this.publication = publication;
this.authors = authors;
}

}
[/code]

We populate a list with some values for this model bean and this list would be converted to JSON output. Note the use of @SerializedName annotation in the model class. This indicates the name used for the attribute in the json output. We populate the list of books using:

[code lang=”java”]
private static List<Book> populateBooks(){

List<Book> myBooks = new ArrayList<Book>();
Book book = new Book("007163360X",
"Java Programming",
"McGraw-Hill Osborne",
"Dr (Poornachandra) Sarang");
myBooks.add(book);

book = new Book("1849516626",
"Apache Tomcat 7 Essentials",
"Tanuj Khare",
"Packt Press");
myBooks.add(book);

book = new Book("007179431X",
"Web Developer’s Cookbook",
"Robin Nixon",
"McGraw-Hill Osborne");
myBooks.add(book);

book = new Book("9781935182962",
"Practical Unit Testing",
"Ken Rimple & Srini Penchikala",
"Manning");
myBooks.add(book);

return myBooks;
}
[/code]

Once we have a list, we need to serialize it to JSON, for that we need to setup a Type information for generic List, this is not possible out of the box in Java and hence we would make use of com.google.gson.reflect.TypeToken class in the GSON API, to create the type information like:

[code lang=”java”]
// Get the type information for the List<Book>
Type listType = new TypeToken<List<Book>>(){}.getType();
[/code]

Next up is to use this type information along with the list of books and pass it to the toJson method to obtain the JSON output.

The complete code:

[code lang=”java”]
import com.google.gson.Gson;
import com.google.gson.annotations.SerializedName;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

public class JsonCreatorDemo {

/**
* Populate the Books information into a List
* @return
*/
private static List<Book> populateBooks(){

List<Book> myBooks = new ArrayList<Book>();
Book book = new Book("007163360X",
"Java Programming",
"McGraw-Hill Osborne",
"Dr (Poornachandra) Sarang");
myBooks.add(book);

book = new Book("1849516626",
"Apache Tomcat 7 Essentials",
"Tanuj Khare",
"Packt Press");
myBooks.add(book);

book = new Book("007179431X",
"Web Developer’s Cookbook",
"Robin Nixon",
"McGraw-Hill Osborne");
myBooks.add(book);

book = new Book("9781935182962",
"Practical Unit Testing",
"Ken Rimple & Srini Penchikala",
"Manning");
myBooks.add(book);

return myBooks;
}

public static void main(String [] args){

List<Book> myBooks = populateBooks();

Gson myGson = new Gson();

// Get the type information for the List<Book>
Type listType = new TypeToken<List<Book>>(){}.getType();

// Serialize the List of books into JSON
System.out.println(myGson.toJson(myBooks,listType));

}
}

class Book{

@SerializedName("isbn")
String isbn;

@SerializedName("title")
String title;

@SerializedName("publication")
String publication;

@SerializedName("authors")
String authors;

public Book ( String isbn,
String title,
String publication,
String authors)
{
this.isbn = isbn;
this.title = title;
this.publication = publication;
this.authors = authors;
}

}
[/code]

JSON Output:

[code]
[
{
"isbn":"007163360X",
"title":"Java Programming",
"publication":"McGraw-Hill Osborne",
"authors":"Dr (Poornachandra) Sarang"
},
{
"isbn":"1849516626",
"title":"Apache Tomcat 7 Essentials",
"publication":"Tanuj Khare",
"authors":"Packt Press"
},
{
"isbn":"007179431X",
"title":"Web Developeru0027s Cookbook",
"publication":"Robin Nixon",
"authors":"McGraw-Hill Osborne"
},
{
"isbn":"9781935182962",
"title":"Practical Unit Testing",
"publication":"Ken Rimple u0026 Srini Penchikala",
"authors":"Manning"
}
]
[/code]

Filed Under: Java Tagged With: gson, JSON

Parsing JSON using Java and GSON library

April 30, 2012 by Mohamed Sanaulla Leave a Comment

In my previous post here, I gave a brief overview of JavaScript Object Notation (JSON). In this post I would go a bit further and show how one can parse the JSON documents into Java objects using the GSON library. The JSON data for this tutorial was obtained from:

also read:

  • JSON Tutorials
  • Java EE Tutorials
  • Design Patterns Tutorials
  • Java File IO Tutorials
[code lang="java"] [
{
"id":"6253282",
"name":"Twitter API",
"screen_name":"twitterapi",
"url":"http://dev.twitter.com",
"followers_count":1004641,
"friends_count":33,
"favourites_count":24,
"statuses_count":3277
},
{
"id":"15082387",
"name":"Sanaulla",
"screen_name":"sanaulla",
"url":"http://blog.sanaulla.info",
"followers_count":241,
"friends_count":302,
"favourites_count":41,
"statuses_count":1876
}
][/code]

Let me call this file as twitterUser.json. It is an array of user profile data where each user profile contains: name, id, screen_name, url, followers_count, friends_count, favourites_count and statuses_count. In order to run the following code, you need to download the GSON API jar from here and add it to your classpath. Moving further, we need to create a Model class which would hold the data obtained from JSON document.

[code lang="java"]
/**
* Model class for storing the selected few attributes
* for a Twitter User profile.
*/
class TwitterUser{
private String id;
private String name;
private String screen_name;
private String url;
private int friends_count;
private int followers_count;
private int favourites_count;
private int statuses_count;
public TwitterUser(){
}
@Override
public String toString(){
return "Name: "+this.name+"n" +
"Screen Name: "+this.screen_name+"n" +
"Number of Friends: "+ this.friends_count + "n" +
"Number of Followers: "+ this.followers_count +"n" +
"Number of Status updates: "+this.statuses_count +"n" +
"Number of favorites: "+this.favourites_count +"n";
}
}[/code]

Before putting forth the code, let me brief about the classes where are used for parsing the Json:

  • com.google.gson.Gson:
    This is the main class for using Gson. Gson is typically used by first constructing a Gson instance and then invoking toJson(Object) or fromJson(String, Class) methods on it.
  • com.google.gson.JsonParser:
    A parser to parse Json into a parse tree of JsonElements
  • com.google.gson.stream.JsonReader:
    Reads a JSON encoded value as a stream of tokens. This stream includes both literal values (strings, numbers, booleans, and nulls) as well as the begin and end delimiters of objects and arrays.
  • com.google.gson.JsonArray:
    A class representing an array type in Json. An array is a list of JsonElements each of which can be of a different type.
  • com.google.gson.JsonElement:
    A class representing an element of Json. It could either be a JsonObject, a JsonArray, a JsonPrimitive or a JsonNull.

Reading the JSON document using JsonReader, assuming the document is present in the file systems:

[code lang="java"] JsonReader reader = new JsonReader(
new InputStreamReader(new FileInputStream(this.jsonSource)));[/code]

JsonReader has a constructor which takes in an instance of a Reader, in our case we use the InputStreamReader and pipe it to a FileInputStream.

Once we are able to read the json data, we go ahead and use JsonParser to parse the contents and obtain the array of objects which the json document stores. There is an another way to do this with out using the JsonParser explicitly, but lets stick to this as its more clearer.

[code lang="java"]
JsonParser jsonParser = new JsonParser();
JsonArray userarray= jsonParser.parse(jsonReader).getAsJsonArray();
[/code]

parse(JsonReader) method of the JsonParser, parses the given Json and creates a parse tree of JsonElements. And the method getAsJsonArray() returns the parsed Json as an array of json objects. In our document we are sure that the document is an array of json objects (recall, the [ ] stands for representing the arrays in json). Suppose you were not sure if those are arrays, then you can use isJsonArray() method of the JsonElement class.

Next up, is to traverse through the array and populate the data from the json object in to our model bean TwitterUser which we had defined at the beginning.

[code lang="java"] List twitterUsers = new ArrayList&amp;amp;lt;&amp;amp;gt;();
for ( JsonElement aUser : userArray ) {
TwitterUser aTwitterUser = myGson.fromJson(aUser, TwitterUser.class);
twitterUsers.add(aTwitterUser);
}[/code]

For each element in the JsonArray we use Gson.fromJson() to populate the data in the json object into the type defined by TwitterUser.class. How it works behind the scene is:

  • It creates a new instance of TwitterUser, by invoking the default constructor.
  • Sets the values of the attributes in the TwitterUser class with those obtained from the json array element. If you closely look at the names of the attributes in the TwitterUser class and the ones in the Json document- they are exactly similar- something like- screen_name, friends_count, followerr_count and so on.

The fromJson method in Gson has been overloaded to support multiple types of parameters, and from that we are using the fromJson(JsonElement json, Class<T> classOfT) version.

Now just to confirm we have parsed the correct data, iterate through the user list:

[code lang="java"] for ( TwitterUser tUser : twitterUsers)
{
System.out.println(tUser);
}[/code]

The complete source for the code is given below:

[code lang="java"] import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.google.gson.stream.JsonReader;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class JsonParserDemo {

private String jsonSource;
private boolean sourceFromFile;
public JsonParserDemo(String jsonSource, boolean sourceFromFile){
this.jsonSource = jsonSource;
this.sourceFromFile = sourceFromFile;
}
public static void main(String[] args){
JsonParserDemo jsonParserDemo =
new JsonParserDemo("/home/mohamed/twitterUser.json", true);
try(JsonReader jsonReader = jsonParserDemo.getJsonReader()){
Gson myGson = new Gson();
JsonParser jsonParser = new JsonParser();
JsonArray userArray =&amp;amp;nbsp; jsonParser.parse(jsonReader).getAsJsonArray();
List twitterUsers = new ArrayList&amp;amp;lt;&amp;amp;gt;();
for ( JsonElement aUser : userArray ){
TwitterUser aTwitterUser = myGson.fromJson(aUser, TwitterUser.class);
twitterUsers.add(aTwitterUser);
}
for ( TwitterUser tUser : twitterUsers){
System.out.println(tUser);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

/**
* Obtain the JsonReader for the given source details.
* @return the JsonReader instance
* @throws FileNotFoundException
*/
private JsonReader getJsonReader () throws FileNotFoundException{
JsonReader reader = null;
if (sourceFromFile){
reader = new JsonReader(
new InputStreamReader(new FileInputStream(this.jsonSource)));
}
return reader;
}
}

/**
* Model class for storing the selected few attributes
* for a Twitter User profile.
*/
class TwitterUser{
private String id;
private String name;
private String screen_name;
private String url;
private int friends_count;
private int followers_count;
private int favourites_count;
private int statuses_count;

public TwitterUser(){
}

@Override
public String toString(){
return "Name: "+this.name+"n" +
"Screen Name: "+this.screen_name+"n" +
"Number of Friends: "+ this.friends_count + "n" +
"Number of Followers: "+ this.followers_count +"n" +
"Number of Status updates: "+this.statuses_count +"n" +
"Number of favorites: "+this.favourites_count +"n";
}
}[/code]

Filed Under: Java Tagged With: gson, JSON

Follow Us

  • Facebook
  • Pinterest

As a participant in the Amazon Services LLC Associates Program, this site may earn from qualifying purchases. We may also earn commissions on purchases from other retail websites.

JavaBeat

FEATURED TUTORIALS

Answered: Using Java to Convert Int to String

What is new in Java 6.0 Collections API?

The Java 6.0 Compiler API

Copyright © by JavaBeat · All rights reserved