2

TL; DR

How to migrate POJOs with ISO8601 string datetime fields to Google Firebase Database, allowing automatic deserialization with Google GSON?

Description

Given the follwing POJO written using Jackson annotations:

    @JsonIgnoreExtraProperties(ignoreUnknown = true)
    public class ChatMessage {

        public String name;
        public String message;

        @JsonFormat(
            shape = JsonFormat.Shape.STRING,
            pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
        )
        public Date createdAt;

        @JsonFormat(
            shape = JsonFormat.Shape.STRING,
            pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
        )
        public Date updatedAt;

        @JsonIgnore
        public String ignoreThisField;

    }

According to Firebase Database migration for Android, this is how and ChatMessage would look using only GSON:

public class ChatMessage {

    public String name;
    public String message;

    public Date createdAt;
    public Date updatedAt;

    @Exclude
    public String ignoreThisField;
}

I have already seeing solutions using custom deserializers, but it would require rewrite dozens of objects.

JP Ventura
  • 5,564
  • 6
  • 52
  • 69

1 Answers1

1

Based on the custom (de)serializer post, I created a Mapper class that automatically deserialize ISO 8601 string dates into Date:

public class Mapper {

    private static Gson GSON = new GsonBuilder()
            .setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
            .create();

    public static <T> T fromJson(Object object, Class<T> type) {
        String jsonString = GSON.toJson((HashMap<String, JSONObject>) object);
        return GSON.fromJson(jsonString, type);
    }

    public static String toJson(Object object) {
        return GSON.toJson(object);
    }

}

and then ChatMessage can be obtained from

ChatMessage msg = Mapper.fromJson(dataSnapshot.getValue(), ChatMessage.class);
Timber.d(Mapper.toJson(msg));
JP Ventura
  • 5,564
  • 6
  • 52
  • 69