I have a User object with this structure:
class User {
private String id;
private String name;
private Map<String, Object> properties;
// GETTERS & SETTERS
}
I have a JSON String with this structure:
{
"user": {
"id:"123456789",
"name:"azerty",
"emailHash":"123456789", // not used in User class
"properties": {
"p1":1,
"p2":"test",
"p3":[1, 2, 3, 4],
"p4":{
etc...
}
}
}
}
Properties' keys are String, Properties' values can be a String, int, Array, boolean, Map etc.
I try to deserialize this JSON string with Gson like that:
JsonParser parser = new JsonParser();
JsonElement element = parser.parse(jsonString);
JsonObject object = element.getAsJsonObject();
GsonBuilder builder = new GsonBuilder();
builder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
Gson gson = builder.create();
User user = (User) gson.fromJson(object.get("user"), new TypeToken<User>() {}.getType());
Fields 'id' and 'name' are correctly injected but the field 'properties' stays null.
Do you know what I'm doing wrong?
Thanks in advance for your help!
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…