38

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

“gson joda”在谷歌上的热门搜索是这个页面:

它为org.joda.time.DateTime. 此链接也是GSON 用户指南中引用的内容。

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

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

4

6 回答 6

42

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

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);
于 2014-03-21T09:02:14.570 回答
14

我在我的项目中使用下一个

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)); 
   }
}
于 2013-02-21T10:21:54.927 回答
14

我使用上面的答案做了一个小助手,它将处理包含 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;
}
于 2017-09-12T17:28:54.287 回答
12

向 GSON 注册一个 TypeAdapter 以包装 Joda 预配置格式化程序的使用,请参阅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"}));
    }
}
于 2016-02-22T16:03:35.343 回答
0

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

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

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

于 2013-02-21T09:13:52.160 回答
0

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

于 2013-02-21T09:16:02.707 回答