0

Android chat crashes on DataSnapshot.getValue() for timestamp

I'm trying to add a timestamp property to my POJO. The solution above tells jackson to ignore the real data member which is used by the application. I'm using AutoValue and can't figure out how I could annotate my class to get it to work.

@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);
    }
}

I tried using a custom serializer:

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

but that wrote the string date: "{.sv=timestamp}" to firebase instead of generating the timestamp

Community
  • 1
  • 1
Vinay Nagaraj
  • 1,162
  • 14
  • 26
  • please read the answer in the link you already know: "Firebase.ServerValue.TIMESTAMP is set as a Map (containing {.sv: "timestamp"}) which tells Firebase to populate that field with the server's time. When that data is read back, it is the actual unix time stamp which is a Long" (.sv=timestamp is a placeholder filled by the firebase server, you have to send it to fb and the result will contain the expected time) – Meiko Rachimow Apr 12 '16 at 17:33
  • Yes, but instead of making two POJOs, one for writes/serialization with the map property and one for reads with the long, I wanted to know if its possible to annotate my autovalue class to be able to do it using one. – Vinay Nagaraj Apr 12 '16 at 17:59

1 Answers1

0

Caught my mistake:

@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);
    }
}
Vinay Nagaraj
  • 1,162
  • 14
  • 26