如何为Gson编写自定义的JSON解串器?

我有一个Java类,用户:

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

我收到一个包含来自webservice的用户对象的JSON列表:

 [{"id":1,"name":"Jonas","update_date":"1300962900226"}, {"id":5,"name":"Test","date_date":"1304782298024"}] 

我试图写一个自定义的反序列化器:

 @Override public User deserialize(JsonElement json, Type type, JsonDeserializationContext context) throws JsonParseException { return new User( json.getAsJsonPrimitive().getAsInt(), json.getAsString(), json.getAsInt(), (Timestamp)context.deserialize(json.getAsJsonPrimitive(), Timestamp.class)); } 

但是我的反序列化器不起作用。 我怎样才能为Gson编写一个自定义的JSON解串器?

 @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())); } 

我假设用户类具有适当的构造函数。

我会采取稍微不同的方法,如下所示,以尽量减少在我的代码中的“手动”解析,因为不必要的做法有些失败,为什么我会使用像Gson的API的第一位的目的。

 // output: // [User: id=1, name=Jonas, updateDate=2011-03-24 03:35:00.226] // [User: id=5, name=Test, updateDate=2011-05-07 08:31:38.024] // using java.sql.Timestamp public class Foo { static String jsonInput = "[" + "{\"id\":1,\"name\":\"Jonas\",\"update_date\":\"1300962900226\"}," + "{\"id\":5,\"name\":\"Test\",\"update_date\":\"1304782298024\"}" + "]"; public static void main(String[] args) { GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES); gsonBuilder.registerTypeAdapter(Timestamp.class, new TimestampDeserializer()); Gson gson = gsonBuilder.create(); User[] users = gson.fromJson(jsonInput, User[].class); for (User user : users) { System.out.println(user); } } } class User { int id; String name; Timestamp updateDate; @Override public String toString() { return String.format( "[User: id=%1$d, name=%2$s, updateDate=%3$s]", id, name, updateDate); } } class TimestampDeserializer implements JsonDeserializer<Timestamp> { @Override public Timestamp deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { long time = Long.parseLong(json.getAsString()); return new Timestamp(time); } } 

(这里假定原始问题中的“date_date”应该是“update_date”。)