是否有GSON Joda Time序列化程序的标准实现?

问题描述 投票:34回答:6

我正在使用GSON将一些对象图序列化为JSON。这些对象图使用Joda Time实体(DateTimeLocalTime等)。

谷歌“gson joda”的热门歌曲是这个页面:

它为org.joda.time.DateTime提供了类型适配器的源代码。此链接也是GSON User Guide中引用的内容。

我希望找到一个包含joda-time序列化程序的预卷库,我可以将其作为Maven依赖项引用 - 但我找不到一个。

有吗?或者我被迫在我自己的项目中复制该片段?

java gson jodatime
6个回答
37
投票

我决定推出自己的开源软件 - 你可以在这里找到它:

https://github.com/gkopff/gson-jodatime-serialisers

这是Maven的详细信息(查看最新版本的中心):

<dependency>
  <groupId>com.fatboyindustrial.gson-jodatime-serialisers</groupId>
  <artifactId>gson-jodatime-serialisers</artifactId>
  <version>1.6.0</version>
</dependency>

这是一个如何驱动它的快速示例:

Gson gson = Converters.registerDateTime(new GsonBuilder()).create();
SomeContainerObject original = new SomeContainerObject(new DateTime());

String json = gson.toJson(original);
SomeContainerObject reconstituted = gson.fromJson(json, SomeContainerObject.class);

14
投票

我在我的项目中使用next

public final class DateTimeDeserializer implements JsonDeserializer<DateTime>, JsonSerializer<DateTime>
{
   static final org.joda.time.format.DateTimeFormatter DATE_TIME_FORMATTER =
      ISODateTimeFormat.dateTime().withZone(DateTimeZone.UTC);

   @Override
   public DateTime deserialize(final JsonElement je, final Type type,
                           final JsonDeserializationContext jdc) throws JsonParseException
   {
      return je.getAsString().length() == 0 ? null : DATE_TIME_FORMATTER.parseDateTime(dateAsString);
   }

   @Override
   public JsonElement serialize(final DateTime src, final Type typeOfSrc,
                                final JsonSerializationContext context)
   {
      return new JsonPrimitive(src == null ? StringUtils.EMPTY :DATE_TIME_FORMATTER.print(src)); 
   }
}

11
投票

使用GSON注册TypeAdapter以包装使用Joda预配置的Formatters,请参阅http://www.joda.org/joda-time/apidocs/org/joda/time/format/ISODateTimeFormat.html

import java.lang.reflect.Type;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import java.lang.reflect.Type;
import org.joda.time.DateTime;
import org.joda.time.format.ISODateTimeFormat;

public class JodaDateTimeWithGson {

    public static void main(String[] args) {
        Gson gson = new GsonBuilder()
            .registerTypeAdapter(DateTime.class, new JsonSerializer<DateTime>(){
                @Override
                public JsonElement serialize(DateTime json, Type typeOfSrc, JsonSerializationContext context) {
                    return new JsonPrimitive(ISODateTimeFormat.dateTime().print(json));
                }
            })
            .create()
            ;

        // Outputs ["20160222T15:58:33.218Z",42,"String"]
        System.out.println(gson.toJson(new Object[] {DateTime.now(), 42, "String"}));
    }
}

6
投票

我使用上面的答案做了一个小助手,它将处理包含DateTime变量的模型对象的序列化和反序列化。

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

1
投票

在我看来,你没有这种类型的库是很正常的。

乍一看它可能看起来很简单,但风险在于你最终会有很多依赖项(有些是在编译时,有些是在运行时),并且要确保不会创建不需要的依赖项并不容易。

对于你的情况,这应该没问题,因为我认为这只是一个运行时依赖项(如果不使用JODA,那么使用serializerLib的项目不应该需要JODA lib)。但对于其他一些案例,这可能会变得丑陋。


0
投票

复制该片段,很多人使用不同的日期字符串格式,从而混淆任何库创建。

© www.soinside.com 2019 - 2024. All rights reserved.