Thursday, 15 October 2015

How to convert JSON to / from Java Object Gson Example

Today we will learn how to use Gson, JSON library, to convert json to/from java object.
JSON is stand for JavaScript Object Notation

we will use gson library's two method for this purpose

1. fromJson() – Convert JSON into Java object
2. toJson() – Convert Java object to JSON format

Firstly i have create a maven project and add gson dependency in pom

<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.4</version>
</dependency>

if you will create java project then download gson jar.

Step 1: Cretae a pojo 


package com.jp.json;

public class Student {
private int id;
private String  name;

public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}

}


Step 2:   Convert JSON to Java Object Gson Example


package com.jp.json;

import com.google.gson.Gson;

public class JSONToObject {

public static void main(String[] args) {

String json = "{\"id\":1," +
" \"name\" : \"json\" }";

System.out.println(" json string ="+json);
Gson gson = new Gson();

Student stu = gson.fromJson(json, Student.class);

System.out.println(" values of java object ");

System.out.println(" id ="+ stu.getId() +" name ="+ stu.getName());

}

}


Output:

 json string ={"id":1, "name" : "json" }
 values of java object
 id =1 name =json


Step 3:   convert Java Object To JSON  Gson Example


package com.jp.json;

import com.google.gson.Gson;

public class ObjectToJSON {

public static void main(String[] args) {

Student stu = new Student();
stu.setId(10);
stu.setName("java");

System.out.println(" values of java object ");
System.out.println(" id ="+ stu.getId() +" name ="+ stu.getName());

Gson gson = new Gson();

String json = gson.toJson(stu);

System.out.println(" json string ="+ json);



}

}




Output:

 values of java object
 id =10 name =java
 json string ={"id":10,"name":"java"}




Related Posts:



How To Read JSON In Java (Set 1) 

How To Read JSON In Java (Set 2) 

How To Read JSON In Java (Set 3) 





No comments:

Post a Comment