When the JSON field name doesn’t exactly match the Java object field names, we can use @SerializedName
to change the JSON’s matching field name in Gson.
Table of contents:
- 1. Setup Google Gson
- 2. JSON Unrecognized Field
- 3. Custom field name with @SerializedName
- 4. Download Source Code
- 5. References
P.S Tested with Gson 2.10.1
1. Setup Google Gson
Declare gson
in the pom.xml
.
pom.xml
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.10.1</version>
</dependency>
2. JSON Unrecognized Field
Review the JSON data below. The JSON field name nick_name
doesn’t match the Person
name. If we use Gson to do the data binding, the Person
name will be null
.
{
"nick_name": "mkyong",
"age": 42
}
Person.java
public class Person {
private String name;
private int age;
//getters, setters, constructors and etc...
}
GsonCustomFieldNameExample.java
package com.mkyong.json.gson;
import com.google.gson.Gson;
import com.mkyong.json.model.Person;
public class GsonCustomFieldNameExample {
public static void main(String[] args) {
String json = "{\"nick_name\":\"mkyong\",\"age\":42}";
Gson gson = new Gson();
// nick_name => name?
Person person = gson.fromJson(json, Person.class);
System.out.println(person);
}
}
Output
Person{name='null', age=42}
3. Custom field name with @SerializedName
In Gson, we can use @SerializedName
to change the JSON’s matching field name.
Person.java
package com.mkyong.json.model;
import com.google.gson.annotations.SerializedName;
public class Person {
// custom field name
// match `nick_name` to `name`
@SerializedName("nick_name")
private String name;
private int age;
//getters, setters, constructors and etc...
}
Below is the JSON serialization and deserialization example using Gson to match JSON field name nick_name
to the Person field name name
.
GsonCustomFieldNameExample.java
package com.mkyong.json.gson;
import com.google.gson.Gson;
import com.mkyong.json.model.Person;
public class GsonCustomFieldNameExample {
public static void main(String[] args) {
String json = "{\"nick_name\":\"mkyong\",\"age\":42}";
Gson gson = new Gson();
// Deserialize JSON to Java object
Person person = gson.fromJson(json, Person.class);
// Serialize Java object back to JSON
System.out.println(person);
String newJson = gson.toJson(person);
System.out.println("Serialized JSON: " + newJson);
}
}
Output
Person{name='mkyong', age=42}
Serialized JSON: {"nick_name":"mkyong","age":42}
4. Download Source Code
$ git clone https://github.com/mkyong/java-json
$ cd gson
5. References
- Google Gson Github
- How to convert Java object to / from JSON using Gson
- How to parse JSON using Gson
- Jackson Custom field name with @JsonProperty
The post Gson custom field name with @SerializedName appeared first on Mkyong.com.