Last Updated: January 11, 2021
·
2.313K
· anmol5

How to convert JSON to / from Java Object Gson Example

We will use gson library for this purpose. There is
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>

Step 1: Cretae a pojo accordingly your requirement
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”}