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
pom.xml
<dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.8.5</version> </dependency>
2. Java Object
For testing later.
Staff.java
package com.favtuts.json.gson; 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 public Staff(String name, int age, String[] position, List<String> skills, Map<String,BigDecimal> salary) { this.name = name; this.age = age; this.position = position; this.skills = skills; this.salary = salary; } public Staff() { } //getters and setters @Override public String toString() { return "Staff{" + " name='" + getName() + "'" + ", age='" + getAge() + "'" + ", position='" + Arrays.asList(getPosition()) + "'" + ", skills='" + getSkills() + "'" + ", salary='" + getSalary() + "'" + "}"; } public String getName() { return this.name; } public void setName(String name) { this.name = name; } public int getAge() { return this.age; } public void setAge(int age) { this.age = age; } public String[] getPosition() { return this.position; } public void setPosition(String[] position) { this.position = position; } public List<String> getSkills() { return this.skills; } public void setSkills(List<String> skills) { this.skills = skills; } public Map<String,BigDecimal> getSalary() { return this.salary; } public void setSalary(Map<String,BigDecimal> salary) { this.salary = salary; } }
3. Java Objects to JSON
3.1 In Gson, we can use gson.toJson()
to convert Java objects to JSON.
GsonExample1.java
package com.favtuts.json; import java.io.FileWriter; import java.io.IOException; import java.math.BigDecimal; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import com.favtuts.json.gson.Staff; import com.google.gson.Gson; import com.google.gson.GsonBuilder; public class GsonParseJSON { public static void main(String[] args) { javaObjectsToJSON(); } static void javaObjectsToJSON() { // 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("/home/tvt/workspace/favtuts/staff.json")) { gson.toJson(staff, writer); } catch (IOException e) { e.printStackTrace(); } } private static Staff createStaffObject() { Staff staff = new Staff(); staff.setName("favtuts"); 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
c:\\test\\staff.json
{
"name": "favtuts",
"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.
GsonExample2.java
package com.favtuts.json; import java.io.FileReader; import java.io.IOException; import java.io.Reader; import com.favtuts.json.gson.Staff; import com.google.gson.Gson; public class GsonParseJSON { public static void main(String[] args) { jsonToJavaObjects(); } static void jsonToJavaObjects() { Gson gson = new Gson(); try (Reader reader = new FileReader("/home/tvt/workspace/favtuts/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='favtuts', 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.
GsonExample3.java
package com.favtuts.json; import com.google.gson.Gson; import com.google.gson.GsonBuilder; public class GsonParseJSON { public static void main(String[] args) { printJSONcompactMode(); } static void printJSONcompactMode() { // 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.
GsonExample4.java
package com.favtuts.json; import com.google.gson.Gson; import com.google.gson.GsonBuilder; public class GsonParseJSON { public static void main(String[] args) { printJSONprettyMode(); } static void printJSONprettyMode() { // 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
ExcludeField.java
package com.favtuts.json.gson; 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.
CustomExclusionStrategy.java
package com.favtuts.json.gson; 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.
Staff.java
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":"favtuts","age":35}
7. Null Object Support
null
object fields are ignored.
GsonExample5.java
package com.favtuts.json; import com.favtuts.json.gson.Staff; import com.google.gson.Gson; public class GsonParseJSON { public static void main(String[] args) { displayJsonObjectIgnoreNull(); } static void displayJsonObjectIgnoreNull() { Gson gson = new Gson(); Staff staff = createStaffObjectNull(); String json = gson.toJson(staff); System.out.println(json); } private static Staff createStaffObjectNull() { Staff staff = new Staff(); staff.setName("favtuts"); staff.setAge(35); return staff; } }
Output
{"name":"favtuts","age":35}
To display the null value.
Gson gson = new GsonBuilder().serializeNulls().create();
Output
{"name":"favtuts","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("favtuts_name") private String name;
Output
{"favtuts_name":"abc"}
9. Versioning Support
package com.favtuts.json.gson.version; import java.math.BigDecimal; import java.util.Arrays; import java.util.List; import java.util.Map; import com.google.gson.annotations.Since; public class Staff { @Since(1.0) private String name; @Since(2.0) private int age; @Since(3.0) private String[] position; // array private List<String> skills; // list private Map<String, BigDecimal> salary; // map
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
GsonExample4.java
package com.mkyong.json.gson; 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\":\"favtuts\"}, {\"name\":\"laplap\"}]"; List<Staff> list = gson.fromJson(json, new TypeToken<List<Staff>>() {}.getType()); list.forEach(x -> System.out.println(x)); } }
Output
Staff{name='favtuts', 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
GsonExample5.java
package com.favtuts.json.gson; 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\":\"favtuts\", \"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 : favtuts
key : age , value : 33.0
Note
Read more Gson user guide
Download Source Code
$ git clone https://github.com/favtuts/java-core-tutorials-examples
$ cd java-basic/json