• Menu
  • Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

JavaBeat

Java Tutorial Blog

  • 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)
  • 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)

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]

Category: JavaTag: gson, JSON

About Mohamed Sanaulla

In his day job he works on developing enterprise applications using ADF. He is also the moderator of JavaRanch forums and an avid blogger.

Previous Post: « Whats new in Java 7 – try-with-resource construct in Project Coin
Next Post: Embedding HTML into Java Swing Applications »

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Primary Sidebar

Follow Us

  • Facebook
  • Pinterest

FEATURED TUTORIALS

np.zeros

A Complete Guide To NumPy Functions in Python For Beginners

What is new in Java 6.0 Collections API?

The Java 6.0 Compiler API

Introductiion to Jakarta Struts

What’s new in Struts 2.0? – Struts 2.0 Framework

JavaBeat

Copyright © by JavaBeat · All rights reserved
Privacy Policy | Contact