在Java中使用Gson使用@SerializedName注释有什么用?
@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"
}热门推荐
10 儿子立冬祝福语简短独特
11 对当兵的祝福语简短
12 侄儿高考试祝福语简短
13 伴郎红包祝福语朋友简短
14 媳妇生日简短祝福语朋友
15 公司年会祝福语简短最好
16 元旦感恩祝福语简短大全
17 红包祝福语简短10字
18 周六早晨祝福语简短