Skip to content Skip to sidebar Skip to footer

Naming Convention With Firebase Serialization/deserialization?

I wonder to know how Firebase serialize/deserialize POJO object to/from json, does it use Jackson or Gson or any similar library else. I have trouble about naming convention with F

Solution 1:

When reading the data back from the Firebase database you can use the @PropertyName annotation to mark a field to be renamed when being serialized/deserialized, like so:

@IgnoreExtraProperties
class Data {
    @PropertyName("some_field_name")
    public String someFieldName
    @PropertyName("another_field_name")
    private String anotherFieldName;
    publicData() {}
}

Make sure that your field is public and not private or else the annotation will not work (I also believe that Firebase uses Jackson to handle the object mapping under the hood, but don't think you can actually customize HOW it uses it).

Solution 2:

Personally I prefer keeping explicit control over the serialization/deserialization process, and not relying on specific framework and/or annotations.

Your Data class can be simply modified like this :

classData {
    privateString someFieldName;
    privateString anotherFieldName;
    publicData() {}
    publicData(Map<String, Object> map) {
        someFieldName = (String) map.get("some_field_name") ;
        anotherFieldName = (String) map.get("another_field_name") ;
    }

    publicMap<String, Object> toMap() {
        Map<String, Object> map = newHashMap<>();
        map.put("some_field_name", someFieldName);
        map.put("another_field_name", anotherFieldName);
        return map ;
    }
}

For writing value to firebase, simply do :

dbref.setValue(data.toMap());

For reading :

Map<String, Object> map = (Map<String, Object>) dataSnapshot.getValue();
data = newData(map);

They are some advantages with this solution :

  • No assumption is made on underlying json framework
  • No need to use annotations
  • You can even further decouple you Object model from your Json model by externalizing the methods toMap() and constructor to a DataMapper (snippet hereunder)

publicstaticDatafromMap(Map<String, Object> map) {
    String someFieldName = (String) map.get("some_field_name") ;
    String anotherFieldName = (String) map.get("another_field_name") ;
    returnnewData(someFieldName, anotherFieldName);
}

publicstaticMap<String, Object> toMap(Data data) {
    Map<String, Object> map = newHashMap<>();
    map.put("some_field_name", data.getSomeFieldName());
    map.put("another_field_name", data.getAnotherFieldName());
    return map ;
}

Post a Comment for "Naming Convention With Firebase Serialization/deserialization?"