我目前正在使用 Gson 库将 json 文件反序列化为一些 java 类实例。一切似乎都工作正常,但我遇到了具有小写字段定义的嵌套类的问题。我的 FieldNamingPolicy 设置为 FieldNamingPolicy.UPPER_CAMEL_CASE,它适用于层次结构中的所有内容,但嵌套类中具有小写(而不是 PascalCase)字段名称的项目除外。
在解析的 JSON 中使用混合大小写是否有什么特殊之处?
我不确定我的解释是否有意义,所以这里是我的 json 的样子以及我遇到的问题的人为示例:
{
"Name": "David",
"City": "Los Angeles",
"Website": "http://www.example.org/1",
"Contact": {
"AllowPhone": "true",
"Priority": "10",
"Address": {
"street": "1234 Example St",
"city": "Los Angeles",
"state": "CA",
"phone": "(777)777-7777"
}
}
}
我有基于此层次结构的类:
- PersonModel(包含姓名、城市、州、网站和联系人字段)
- ContactModel(包含“允许电话”、“优先级”、“地址”字段)
- AddressModel(包含街道、城市、州、电话字段)
类的示例:
public class PersonModel{
@Expose
String name;
@Expose
String city;
@Expose
String website;
@Expose
ContactModel contact;
/* getters for all the above defined */
}
public class ContactModel{
@Expose
String allowPhone;
@Expose
int priority;
@Expose
AddressModel address;
/* getters for all the above defined */
}
public class AddressModel{ /* fields are lower case! */
@Expose
String street;
@Expose
String city;
@Expose
String state;
@Expose
String phone;
/* getters for all the above defined */
}
当我尝试将 json 反序列化到我的类结构中时,Person 和 Contact 按预期工作。我什至得到了一个 AddressModel 的实例。然而,AddressModel 实例上的字段均为空。
任何人都可以向我指出解决该案例问题的方法,或者如果还有其他问题,可以提供调整方法吗?
最佳答案
正如javadoc所述,GsonBuilder#setFieldNamingPolicy(FieldNamingPolicy)
Configures Gson to apply a specific naming policy to an object's field during serialization and deserialization.
因此字段映射如下
Java name | Json name
name | Name
还必须进行反序列化。它们适用于您的 PersonModel
和 ContactModel
,因为该策略成立。
但是,对于您的 AddressModel
类,它看起来像
Java name | Json name
street | street
因此该策略没有得到遵守,Gson 找不到这些字段来反序列化它们。
我建议使用 @SerializedName
来准确指定 JSON 中的名称。
关于java - Gson 反序列化 - 映射小写字段的嵌套类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22428630/