How do I write a custom JSON deserializer for Gson?

前端 未结 2 604
青春惊慌失措
青春惊慌失措 2020-11-22 09:34

I have a Java class, User:

public class User
{
    int id;
    String name;
    Timestamp updateDate;
}

And I receive a JSON list containin

2条回答
  •  无人及你
    2020-11-22 09:59

    @Override
    public User deserialize(JsonElement json, Type type,
            JsonDeserializationContext context) throws JsonParseException {
    
        JsonObject jobject = json.getAsJsonObject();
    
        return new User(
                jobject.get("id").getAsInt(), 
                jobject.get("name").getAsString(), 
                new Timestamp(jobject.get("update_date").getAsLong()));
    }
    

    I'm assuming User class has the appropriate constructor.

提交回复
热议问题