【问题标题】:Saving firebase ServerValue.TIMESTAMP on AutoValue POJOs在 AutoValue POJO 上保存 firebase ServerValue.TIMESTAMP
【发布时间】:2016-04-12 16:56:28
【问题描述】:

Android chat crashes on DataSnapshot.getValue() for timestamp

我正在尝试将时间戳属性添加到我的 POJO。上面的解决方案告诉杰克逊忽略应用程序使用的真实数据成员。我正在使用 AutoValue,但不知道如何注释我的课程以使其正常工作。

@AutoValue
public abstract class Pojo {

    @JsonProperty("id") public abstract String id();
    @JsonProperty("name") public abstract String name();
    @JsonProperty("date") public abstract long date();

    @JsonCreator public static Pojo create(String id, String name, long date) {
        return new AutoValue_Pojo(id, name, date);
    }
}

我尝试使用自定义序列化程序:

public class TimeStampSerializer extends JsonSerializer<Long> {
    @Override public void serialize(Long value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
        jgen.writeString(ServerValue.TIMESTAMP.toString());
    }
}

但是将字符串 date: "{.sv=timestamp}" 写入 firebase 而不是生成时间戳

【问题讨论】:

  • 请阅读您已经知道的链接中的答案:“Firebase.ServerValue.TIMESTAMP 设置为地图(包含 {.sv: "timestamp"}),它告诉 Firebase 使用服务器的时间。当该数据被读回时,它是实际的 unix 时间戳,它是一个 Long”(.sv=timestamp 是由 firebase 服务器填充的占位符,您必须将其发送到 fb,结果将包含预期时间)
  • 是的,但不是制作两个 POJO,一个用于使用 map 属性进行写入/序列化,一个用于使用 long 进行读取,我想知道是否可以注释我的自动值类以便能够用一个来做。

标签: android firebase jackson auto-value


【解决方案1】:

发现我的错误:

@AutoValue
public abstract class Pojo {


    @JsonProperty("id") public abstract String id();

    @JsonProperty("name") public abstract String name();

    //Custom serializer
    @JsonSerialize(using = TimestampSerializer.class) @JsonProperty("date") public abstract long date();

    @JsonCreator public static Pojo create(@JsonProperty("id") String id, @JsonProperty("name") String name, @JsonProperty("date") long date) {
        return new AutoValue_Pojo(id, name, date);
    }
}

public class TimestampSerializer extends JsonSerializer<Long> {
    @Override public void serialize(Long value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
        //Use writeObject() instead of writeString()
        jgen.writeObject(ServerValue.TIMESTAMP);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-10
    • 1970-01-01
    • 2020-03-28
    • 1970-01-01
    • 1970-01-01
    • 2017-05-15
    • 2020-04-12
    • 2018-09-17
    相关资源
    最近更新 更多