@SerializedName注解可以用于序列化的场使用不同的名称,而不是实际的字段名称。我们可以提供期望的序列化名称作为注释属性,Gson可以确保使用提供的名称读取或写入字段。
@Retention(value=RUNTIME) @Target(value={FIELD,METHOD}) public @interface SerializedName
import com.google.gson.*; import com.google.gson.annotations.*; public class SerializedNameTest { public static void main(String args[]) { Gson gson = new GsonBuilder().setPrettyPrinting().create(); Person person = new Person(115, "Raja Ramesh", "Hyderabad"); String jsonStr = gson.toJson(person); System.out.println(jsonStr); } } //人类 class Person { @SerializedName("id") private int personId; @SerializedName("name") private String personName; private String personAddress; public Person(int personId, String personName, String personAddress) { this.personId = personId; this.personName = personName; this.personAddress = personAddress; } public int getPersonId() { return personId; } public String getPersonName() { return personName; } public String getPersonAddress() { return personAddress; } }
输出结果
{ "id": 115, "name": "Raja Ramesh", "personAddress": "Hyderabad" }