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

时间:2015-09-15 20:05:44

标签: java json serialization gson jodatime

我希望将Joda-Time Duration实例序列化为一个长度,表示使用Gson的秒数。我的序列化程序类是:

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

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

1 个答案:

答案 0 :(得分:1)

我不建议使用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();