为什么Joda-Time Duration序列化时出现"iMillis"?

Why does "iMillis" appear when serializing of Joda-Time Duration?

我想使用 Gson 将 Joda-Time Duration 实例序列化为表示秒数的 long。我的序列化程序 class 是:

private class DurationSerializer implements JsonSerializer<Duration>
{
  public JsonElement serialize(Duration duration,
                               Type durationType,
                               JsonSerializationContext context)
    {
    return new JsonPrimitive(duration.getStandardSeconds());
    }
}

这个输出是{"iMillis":900000}。我只想要秒数,而不是 iMillis 标签。这可能吗?

我不建议使用 JsonDeserializer,因为它已被弃用,而推荐使用 Streaming API。我不确定你的问题是什么,但我认为它不在 Serializer.

尝试使用 TypeAdapter 代替:

public class DurationTypeAdapter extends TypeAdapter<Duration> {
  public void write(JsonWriter writer, Duration value) throws IOException {
    if (value == null) {
      writer.nullValue();
      return;
    }

    writer.value(duration.getStandardSeconds());
  }

  // implementation of read() is left as an exercise to you
}

这样注册:

GsonBuidler builder = new GsonBuilder();
builder.registerTypeAdapter(new DurationTypeAdapter());
Gson g = builder.create();