Reputation: 10124
I am currently using Gson libraries to deserialize a json file into some java class instances. Everything seems to work fine but I encounter issues with nested classes with lowercase field definitions. My FieldNamingPolicy is set to FieldNamingPolicy.UPPER_CAMEL_CASE which works for everything in the hierarchy except the items in my nested class that have lowercase (as opposed to PascalCase) field names.
Is there something special involved in having mixed cases used in the JSON being parsed?
I'm not sure my explanation makes sense so here is a contrived example of what my json looks like and the problem I'm running into:
{
"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"
}
}
}
I have classes based on this hierarchy:
Examples of the classes:
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 */
}
When I attempt to deserialize json into my class structure Person and Contact work as expected. I even get an instance of AddressModel. However the fields on the instance of AddressModel are all null.
Can anyone point me to either a fix for the case issue or, if there is something else wrong, an adjusted approach?
Upvotes: 1
Views: 675
Reputation: 279890
As the javadoc states, GsonBuilder#setFieldNamingPolicy(FieldNamingPolicy)
Configures Gson to apply a specific naming policy to an object's field during serialization and deserialization.
So fields mapped like
Java name | Json name
name | Name
have to also work for deserialization. They work for your PersonModel
and ContactModel
because the policy holds true.
However, for your AddressModel
class, it looks like
Java name | Json name
street | street
So the policy is not upheld and Gson doesn't find those fields to deserialize them.
I suggest using @SerializedName
to specify exactly what the name in the JSON will be.
Upvotes: 1