How to convert JSON to / from Java Object Gson Example

Convert json to java object or convert java object to json we have multiple methods . In this tutorial we will learn how to use GSON library to convert json to pojo in java or convert java object to json string
JSON is stand for JavaScript Object Notation . We will use GSON library’s two method for this purpose

1. fromJson() – Convert JSON to java object
2. toJson() – Convert Java object to JSON String 

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 have no idea about maven then you can use GSON jar with java project . In this example we have json string which have two key with name id and name have string data type , so here we will create java pojo with field id and name of string type for mapping purpose .

Step 1: Cretae a java 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;
}

}

Now we will see example of how to convert json string to custom object in java and how to convert pojo to json using gson.

Step 2:   Convert JSON to Java Object Using GSON

Converting json to java object we will use fromJson() method of GSON library .

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 using gson

Convert object to json string in java we will use toJson() method of GSON library .

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"}

In this tutorial we have learned how to convert json to pojo in java and how to convert java object to json string using GSON . This tutorial is part of jersey in java . You can learn more about json using these tutorials

Leave a Reply

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

+ 75 = 76