Is there a standard implementation for a GSON Joda Time serialiser?

后端 未结 6 1895
梦毁少年i
梦毁少年i 2020-12-25 11:27

I\'m using GSON to serialise some object graphs to JSON. These objects graphs use Joda Time entities (DateTime, LocalTime etc).

The top Go

6条回答
  •  醉话见心
    2020-12-25 12:05

    I used the answers above to do a little helper that will handle both serialization and deserialization for model objects containing DateTime variables.

        public static Gson gsonDateTime() {
        Gson gson = new GsonBuilder()
                .registerTypeAdapter(DateTime.class, new JsonSerializer() {
                    @Override
                    public JsonElement serialize(DateTime json, Type typeOfSrc, JsonSerializationContext context) {
                        return new JsonPrimitive(ISODateTimeFormat.dateTime().print(json));
                    }
                })
                .registerTypeAdapter(DateTime.class, new JsonDeserializer() {
                    @Override
                    public DateTime deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
                        DateTime dt = ISODateTimeFormat.dateTime().parseDateTime(json.getAsString());
                        return dt;
                    }
                })
                .create();
        return gson;
    }
    

提交回复
热议问题