Java and J2EE Tutorials, Jsp and Servlet Tutorials, Spring MVC, Solr, XML, JSON Examples, Hibernate & Struts 2 Hello World projects



Saturday, 8 June 2013

Json in Java - Convert Json object to Java and Java object to Json

JSON so called 'JavaScript Object Notation' is a lightweight data exchange format, it is a subset of 'JavaScript programming language standard ECMA-262 '. JSON is a language independent data interchange format that is fully supported by java language.

In java there are a number of standards and techniques to deal with JSON, GSON given by Google is the most commonly and easiest way of JSON implementation in java . In today's discussion we will come to know 'How to convert a JSON object to Java' and 'How to convert a Java object to JSON'.

To implement JSON in java using GSON we need to add an external JAR that can be downloaded from Here.

GSON provides two useful methods and everything moven around these two methods.
toJson() – Convert Java object to JSON format
fromJson() – Convert JSON into Java object

In this tutorial we will see step by step explanation and implementation of parse JSON in Java using Gson.


Project Structure

This is the overall project structure for today's discussion. We have added a 'gson' jar under lib folder to make our project to use gson capabilities. 'JavaToJson.java' file contains code for converting java object to json and 'JsonToJava.java' file contains code for convert json object to java. 'json' folder contains 'student.json' file that we will be using to read and convert json from. We have added a domain class 'Student.java' this will be used to carry an object to convert to json and from json. Please make sure you have added 'gson' jar to project's classpath.


Convert Java object to JSON using GSON

Convert java object to json is an easy task, all we need to do is having an java object and use a 'toJson' method from 'Gson' API.

src\com\beingjavaguys\domain\Student.java

This is a simple java domain class to obtain an object so that convert from java to json and json to java can be demonstrated.
package com.beingjavaguys.domain;

import java.util.List;

public class Student {
 
 private int id;
 private String firstName;
 private String lastName;
 private String gender;
 private String city;
 private List<string> interests;

// getters and setters
 public int getId() {
  return id;
 }
 public void setId(int id) {
  this.id = id;
 }
 public String getFirstName() {
  return firstName;
 }
 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }
 public String getLastName() {
  return lastName;
 }
 public void setLastName(String lastName) {
  this.lastName = lastName;
 }
 public String getGender() {
  return gender;
 }
 public void setGender(String gender) {
  this.gender = gender;
 }
 public String getCity() {
  return city;
 }
 public void setCity(String city) {
  this.city = city;
 }
 public List<string> getInterests() {
  return interests;
 }
 public void setInterests(List<string> interests) {
  this.interests = interests;
 }
 
}



src\com\beingjavaguys\core\JavaToJson.java

This is a simple java classes which contains actual code of convert java object to json, we have added some data to Student objcet here. All we did here is obtain an object from Gson and called toJson() method on our student object.
package com.beingjavaguys.core;

import java.util.ArrayList;
import com.beingjavaguys.domain.Student;
import com.google.gson.Gson;

public class JavaToJson {
 public void convertJavaToJson(){
  
  // simple object from student domain class
  Student student = new Student();
  
  // added some data to student's object
  ArrayList<string> interests = new ArrayList<string>();
  interests.add("friends");
  interests.add("women");
  interests.add("chatting");
  
  student.setId(1);
  student.setFirstName("ankush");
  student.setLastName("thakur");
  student.setGender("male");
  student.setInterests(interests);
  
  // obtained Gson object 
  Gson gson = new Gson();
  
  // called toJson() method and passed student object as parameter
  // print generated json to console
  System.out.println(gson.toJson(student));
  
  }
}

Output

This is generated json from student java object.
{"id":1,"firstName":"ankush","lastName":"thakur","gender":"male","city":"gurgaon","interests":["friends","women","chatting"]}


Convert JSON object to Java using GSON

Convert json object to java is an easy task all we need to do is having an json file and reading json from there to convert to java.

Objective JSON file to convert in Java object

This is sample json string written under 'student.json' file, we will read this in our code to convert into a java object.
{"id":1,"firstName":"ankush","lastName":"thakur","gender":"male","city":"gurgaon","interests":["friends","women","chatting"]}

src\com\beingjavaguys\core\JsonToJava.java

We have read json from student.json file and passes the stream to 'fromJson()' method. Than we have iterated the object simply to see how to use data contained in json.
package com.beingjavaguys.core;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;

import com.beingjavaguys.domain.Student;
import com.google.gson.Gson;

public class JsonToJava {
 
 public void jsonToJava(){
  
  try { 
   // obtained a file object from json file
   File file = new File("json/student.json");

   // get json as buffer
   BufferedReader br = new BufferedReader(new FileReader(file));

   // obtained Gson object
   Gson gson = new Gson();

   // called fromJson() method and passed incoming buffer from json file
   // passed student class reference to convert converted result as Student object
   Student student = gson.fromJson(br, Student.class);
   
   // printed student data on console
   System.out.println("id: "+student.getId()+" First Name:"+student.getFirstName()
   +" Last Name: "+student.getLastName()+" Gender: "+student.getGender()+" City: "+student.getCity());
   
   System.out.println("Interests: ");
   for(int i=0;i<=student.getInterests().size()-1;i++){
    System.out.println(student.getInterests().get(i));
   }
   
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  }
  
  
 }
}


Output

This is a screenshot from console, we will get an output like this after conversion is done.


Implementation class code

src\com\beingjavaguys\core\JsonImplementation.java

This is nothing but a simple implementation class having main method, we have called our codes here to demonstrate actual conversion.
package com.beingjavaguys.core;

public class JsonImplementation {
 public static void main(String args[]){

  // java to json conversion
  JavaToJson javaToJson = new JavaToJson();
  javaToJson.convertJavaToJson();
  
  // json to java conversion
  JsonToJava jsonToJava = new JsonToJava();
  jsonToJava.jsonToJava();
  
 }
}



In this particular blog we learn how to parse json in java and came across 'How to convert json object to java using Gson' and 'how to convert java object to json using Gson'. In upcoming blogs we will come across more about json implementations in java and other useful stuff. Read more about XML & JSON under SAX & DOM & Xml parser in Java & JDOM2 & XML parser in Java JSON, and JAXB - Marshalling & Unmarshalling in Java categories.








Thanks for reading !
Being Java Guys Team

Download "JSON to Java & Java to JSON Example Project" from "SkyDrive"





4 comments:

  1. Hi,

    The article was very useful. Thanks for the article. Could you please share the code for getting the below output?
    "From":{
    "Name":"Rad",
    "Address":"blah@gmail.com"
    } using toJson()?

    Rad.

    ReplyDelete
  2. hi friend,
    can you just tell me how to read this json.
    {"filter_level":"medium",
    "contributors":null,
    "text":"Odio qué mi laptop se apague a lo PENDEJO!",
    "geo":null,
    "retweeted":false,
    "in_reply_to_screen_name":null,
    "truncated":false,
    "lang":"es",
    "entities":{"symbols":[],"urls":[],"hashtags":[],"user_mentions":[]},
    "user":{"location":"Mexico City","statuses_count":106640,"is_translator":false},
    "coordinates":null
    }

    Convert Java object to JSON format.
    Convert JSON into Java object.

    ReplyDelete

Like Us on Facebook


Like Us On Google+



Contact

Email: neel4soft@gmail.com
Skype: neel4soft