Gson – How to parse JSON
Gson provide simple toJson()
and fromJson()
methods to convert Java objects to / from JSON.
toJson()
– Java object to JSON
Gson gson = new Gson();
// 1. Java object to JSON file
gson.toJson(obj, new FileWriter("C:\\fileName.json"));
// 2. Java object to JSON string
String json = gson.toJson(obj);
fromJson()
– JSON to Java object
Gson gson = new Gson();
// 1. JSON file to Java object
Object object = gson.fromJson(new FileReader("C:\\fileName.json"), Object.class);
// 2. JSON string to Java object
String json = "{'name' : 'mkyong'}";
Object object = gson.fromJson(json, Staff.class);
1. Download Gson
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.5</version>
</dependency>
2. Java Object
For testing later.
package com.mkyong;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
public class Staff {
private String name;
private int age;
private String[] position; // array
private List<String> skills; // list
private Map<String, BigDecimal> salary; // map
//getters and setters
}
3. Java Objects to JSON
3.1 In Gson, we can use gson.toJson()
to convert Java objects to JSON.
package com.mkyong;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.io.FileWriter;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
public class GsonExample1 {
public static void main(String[] args) {
// pretty print
Gson gson = new GsonBuilder().setPrettyPrinting().create();
Staff staff = createStaffObject();
// Java objects to String
String json = gson.toJson(staff);
//System.out.println(json);
// Java objects to File
try (FileWriter writer = new FileWriter("c:\\test\\staff.json")) {
gson.toJson(staff, writer);
} catch (IOException e) {
e.printStackTrace();
}
}
private static Staff createStaffObject() {
Staff staff = new Staff();
staff.setName("mkyong");
staff.setAge(35);
staff.setPosition(new String[]{"Founder", "CTO", "Writer"});
Map<String, BigDecimal> salary = new HashMap() {{
put("2010", new BigDecimal(10000));
put("2012", new BigDecimal(12000));
put("2018", new BigDecimal(14000));
}};
staff.setSalary(salary);
staff.setSkills(Arrays.asList("java", "python", "node", "kotlin"));
return staff;
}
}
Output
{
"name": "mkyong",
"age": 35,
"position": [
"Founder",
"CTO",
"Writer"
],
"skills": [
"java",
"python",
"node",
"kotlin"
],
"salary": {
"2018": 14000,
"2012": 12000,
"2010": 10000
}
}
4. JSON to Java Objects
4.1 In Gson, we can use gson.fromJson
to convert JSON back to Java objects.
package com.mkyong;
import com.google.gson.Gson;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
public class GsonExample2 {
public static void main(String[] args) {
Gson gson = new Gson();
try (Reader reader = new FileReader("c:\\test\\staff.json")) {
// Convert JSON File to Java Object
Staff staff = gson.fromJson(reader, Staff.class);
// print staff
System.out.println(staff);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Output
Staff{name='mkyong', age=35, position=[Founder, CTO, Writer], skills=[java, python, node, kotlin], salary={2018=14000, 2012=12000, 2010=10000}}
5. Pretty Print JSON
5.1 The default JSON output is compact mode.
package com.mkyong;
import com.google.gson.Gson;
public class GsonExample3 {
public static void main(String[] args) {
// compact print
Gson gson = new Gson();
String[] lang = {"Java", "Node", "Kotlin", "JavaScript"};
String json = gson.toJson(lang);
System.out.println(json);
}
}
Output
["Java","Node","Kotlin","JavaScript"]
5.2 To enable pretty print.
package com.mkyong;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class GsonExample4 {
public static void main(String[] args) {
// pretty print
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String[] lang = {"Java", "Node", "Kotlin", "JavaScript"};
String json = gson.toJson(lang);
System.out.println(json);
}
}
Output
[
"Java",
"Node",
"Kotlin",
"JavaScript"
]
6. Exclude Fields
In Gson, there are many ways to exclude certain fields.
6.1 By default, transient
and static
fields will be excluded. We can override the default by excludeFieldsWithModifiers
If we want to exclude static fields only.
import java.lang.reflect.Modifier;
Gson gson = new GsonBuilder()
.excludeFieldsWithModifiers(Modifier.STATIC)
.create();
If we want to exclude transient and static fields, default.
import java.lang.reflect.Modifier;
Gson gson = new GsonBuilder()
.excludeFieldsWithModifiers(Modifier.STATIC, Modifier.TRANSIENT)
.create();
In this configuration, static and transient fields will be included.
Gson gson = new GsonBuilder()
.excludeFieldsWithModifiers()
.create();
6.2 Exclude fields by @Expose
The @Expose
define which fields to be excluded from serialization and deserialization to JSON. To use @Expose
, we need to create Gson object like this:
Gson gson = new GsonBuilder()
.excludeFieldsWithoutExposeAnnotation()
.create();
If .excludeFieldsWithoutExposeAnnotation()
mode is enabled, all fields without @Expose
will be excluded. For example,
import com.google.gson.annotations.Expose;
public class Staff {
@Expose(serialize = true, deserialize = true)
private String name;
@Expose
private int age;
@Expose(serialize = false, deserialize = true)
private String[] position;
private List<String> skills;
private Map<String, BigDecimal> salary;
If convert above Java object to JSON, the output will be like this
{
"name": "mkyong",
"age": 35
}
6.3 Exclude fields by ExclusionStrategies
, annotation, type, field name and etc. Gson is flexible.
A custom annotation @ExcludeField
package com.mkyong;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD})
public @interface ExcludeField {
}
A ExclusionStrategy
to define what fields should be excluded or skipped.
package com.mkyong;
import com.google.gson.ExclusionStrategy;
import com.google.gson.FieldAttributes;
public class CustomExclusionStrategy implements ExclusionStrategy {
private final Class<?> typeToSkip;
public CustomExclusionStrategy(Class<?> typeToSkip) {
this.typeToSkip = typeToSkip;
}
@Override
public boolean shouldSkipField(FieldAttributes f) {
// if field name 'salary`, skip
if ("salary".equals(f.getName())) {
return true;
}
// if found @ExcludeField, skip
if (f.getAnnotation(ExcludeField.class) != null) {
return true;
}
return false;
}
@Override
public boolean shouldSkipClass(Class<?> clazz) {
return (clazz == typeToSkip);
}
}
Review the staff
object again.
public class Staff {
private String name;
private int age;
@ExcludeField
private String[] position;
private List<String> skills;
private Map<String, BigDecimal> salary;
Enable the ExclusionStrategy
mode.
Gson gson = new GsonBuilder()
.setExclusionStrategies(new CustomExclusionStrategy(List.class)) // exclude all List fields.
.create();
Output, this example, field name salary
, @ExcludeField
fields and List
type fields will be excluded.
{"name":"mkyong","age":35}
7. Null Object Support
null
object fields are ignored.
package com.mkyong;
import com.google.gson.Gson;
public class GsonExample5 {
public static void main(String[] args) {
Gson gson = new Gson();
Staff staff = createStaffObject();
String json = gson.toJson(staff);
System.out.println(json);
}
private static Staff createStaffObject() {
Staff staff = new Staff();
staff.setName("mkyong");
staff.setAge(35);
return staff;
}
}
Output
{"name":"mkyong","age":35}
To display the null value.
Gson gson = new GsonBuilder().serializeNulls().create();
Output
{"name":"mkyong","age":35,"position":null,"skills":null,"salary":null}
8. JSON Field Naming Support
Default
public class Staff {
private String name;
Output
{"name":"abc"}
Custom field name with @SerializedName
public class Staff {
@SerializedName("mkyong_name")
private String name;
Output
{"mkyong_name":"abc"}
9. Versioning Support
import com.google.gson.annotations.Since;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
public class Staff {
@Since(1.0)
private String name;
@Since(2.0)
private int age;
@Since(3.0)
private String[] position;
private List<String> skills;
private Map<String, BigDecimal> salary;
In this example, the field position
(version 3) will be excluded.
Gson gson = new GsonBuilder()
.serializeNulls()
.setVersion(2.0) // version <= 2.0 will be included.
.create();
Output
{"name":null,"age":0,"skills":null,"salary":null}
10. FAQs
Some commonly ask questions.
10.1 Convert a JSON Array to a List of object, using TypeToken
package com.mkyong;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.util.List;
public class GsonExample4 {
public static void main(String[] args) {
Gson gson = new Gson();
String json = "[{\"name\":\"mkyong\"}, {\"name\":\"laplap\"}]";
List<Staff> list = gson.fromJson(json, new TypeToken<List<Staff>>() {}.getType());
list.forEach(x -> System.out.println(x));
}
}
Output
Staff{name='mkyong', age=0, position=null, skills=null, salary=null}
Staff{name='laplap', age=0, position=null, skills=null, salary=null}
10.2 Convert a JSON to a Map
package com.mkyong;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.util.Map;
public class GsonExample5 {
public static void main(String[] args) {
Gson gson = new Gson();
String json = "{\"name\":\"mkyong\", \"age\":33}";
Map<String, Object> map = gson.fromJson(json, new TypeToken<Map<String, Object>>() {}.getType());
map.forEach((x, y) -> System.out.println("key : " + x + " , value : " + y));
}
}
Output
key : name , value : mkyong
key : age , value : 33.0
Read more Gson user guide
What if JSON objects are into an JSON array?
For example
{
“data”:
[
{
“id”: 1000,
“name”: “ABC”
},
{
“id”: 1001,
“name”: “BCD”
},
{
“id”: 1002,
“name”: “CDE”
}
]
}
mkyong, you are the best!
So many your examples (include this one) helps me, you even cant imagine!
Thank you a LOT!
Can you please share the example for complex json like below.
{
“kbaDetails”:[
{
“ques”:”What is your favorite animal?”,
“kba”:”tiger”
},
{
“ques”:”What was the color of the first vehicle you owned?”,
“kba”:”esteem”
},
{
“ques”:”What is your favorite sport to watch?”,
“kba”:”cricket”
},
{
“ques”:”What is your favorite holiday?”,
“kba”:”india”
}
]
}
tes
test