您需要编写一个自定义解串器。您还需要使用
SimpleDateFormat可以实际解析的时区格式。无论是
z也
Z将匹配
-07:00,这是RFC
822时区格式(的一个奇怪的组合
-0700)或者“一般的时区”(
Mountain StandardTime或
MST或
GMT-07:00)。另外,您可以坚持使用完全相同的时区格式,并使用JodaTime的DateTimeFormat。MyCustomClass.java
MyCustomDeserializer.javapublic class MyCustomClass{ Date date; Long value; public MyCustomClass (Date date, Long value) { this.date = date; this.value = value; } @Override public String toString() { return "{date: " + date + ", value: " + value + "}"; }}
GsonTest.javapublic class MyCustomDeserializer implements JsonDeserializer<MyCustomClass>{ private DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssz"); @Override public MyCustomClass deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext ctx) throws JsonParseException { JsonObject obj = json.getAsJsonObject(); Entry<String, JsonElement> entry = obj.entrySet().iterator().next(); if (entry == null) return null; Date date; try { date = df.parse(entry.getKey()); } catch (ParseException e) { e.printStackTrace(); date = null; } Long value = entry.getValue().getAsLong(); return new MyCustomClass(date, value); }}
public class GsonTest{ public static void main(String[] args) { // Note the time zone format tweak (removed the ':') String json = "[{"2011-04-30T00:00:00-0700":100}, {"2011-04-29T00:00:00-0700":200}]"; Gson gson = new GsonBuilder() .registerTypeAdapter(MyCustomClass.class, new MyCustomDeserializer()) .create(); Type collectionType = new TypeToken<Collection<MyCustomClass>>(){}.getType(); Collection<MyCustomClass> myCustomClasses = gson.fromJson(json, collectionType); System.out.println(myCustomClasses); }}
上面的所有代码都在Github上,可以随时克隆(尽管您还将获得用于回答其他问题的代码)。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)