文章17 | 阅读 10711 | 点赞0
本文内容大多基于官方文档和网上前辈经验总结,经过个人实践加以整理积累,仅供参考。
GsonBuilder 类的 setFieldNamingPolicy 和 setFieldNamingStrategy 方法可以定义 POJO 和 JSON 的字段映射规则
示例
POJO
public class User {
private String name;
private String phoneNumber;
public User() {}
public User(String name, String phoneNumber) {
this.name = name;
this.phoneNumber = phoneNumber;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
@Override
public String toString() {
return "User [name=" + name + ", phoneNumber=" + phoneNumber + "]";
}
}
测试代码:
@Test
public void test() throws IOException {
User user = new User("UserX", "160");
Gson gson = new GsonBuilder()
.setFieldNamingPolicy(FieldNamingPolicy.IDENTITY)
.create();
System.out.println(gson.toJson(user));
String userStr = "{\"name\":\"User1\",\"phoneNumber\":\"161\"}";
System.out.println(gson.fromJson(userStr, User.class));
gson = new GsonBuilder()
.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_DASHES)
.create();
System.out.println(gson.toJson(user));
userStr = "{\"name\":\"User1\",\"phone-number\":\"162\"}";
System.out.println(gson.fromJson(userStr, User.class));
gson = new GsonBuilder()
.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
.create();
System.out.println(gson.toJson(user));
userStr = "{\"name\":\"User1\",\"phone_number\":\"163\"}";
System.out.println(gson.fromJson(userStr, User.class));
gson = new GsonBuilder()
.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)
.create();
System.out.println(gson.toJson(user));
userStr = "{\"name\":\"User1\",\"PhoneNumber\":\"164\"}";
System.out.println(gson.fromJson(userStr, User.class));
gson = new GsonBuilder()
.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE_WITH_SPACES)
.create();
System.out.println(gson.toJson(user));
userStr = "{\"name\":\"User1\",\"Phone Number\":\"165\"}";
System.out.println(gson.fromJson(userStr, User.class));
}
运行结果:
测试代码:
@Test
public void test() throws IOException {
User user = new User("UserX", "160");
Gson gson = new GsonBuilder()
.setFieldNamingStrategy(new FieldNamingStrategy() {
public String translateName(Field arg0) {
if (arg0.getName().equals("name")) {
return "custom-name";
} else if (arg0.getName().equals("phoneNumber")) {
return "custom-phone";
}
return null;
}
})
.create();
System.out.println(gson.toJson(user));
String userStr = "{\"custom-name\":\"userN\",\"custom-phone\":\"168\"}";
System.out.println(gson.fromJson(userStr, User.class));
}
运行结果:
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://blog.csdn.net/Silent_Paladin/article/details/54138707
内容来源于网络,如有侵权,请联系作者删除!