问题
I have this class making use of enums. Parsing to Firebase json used to work just fine - using Jackson. While migrating to firebase-database:9.0.0 I get the following:
com.google.firebase.database.DatabaseException: No properties to serialize found on class .... MyClass$Kind
where Kind is the enum declared type. The class:
public class MyClass {
public enum Kind {W,V,U};
private Double value;
private Kind kind;
/* Dummy Constructor */
public MyClass() {}
public Double getValue() {
return value;
}
public void setValue(Double value) {
this.value = value;
}
public Kind getKind() {
return kind;
}
public void setKind(Kind kind) {
this.kind = kind;
}
}
I suspect Firebase no longer uses Jackson when serializing setValue(new MyClass()).
Is there a way to get enum types serialized? Or some means to be explicit with respect to the serializer method?
回答1:
You are right, Firebase Database no longer uses Jackson for serialization or deserialization.
You can represent your enum as a String when talking to Firebase by doing this:
public class MyClass {
public enum Kind {W,V,U};
private Double value;
private Kind kind;
/* Dummy Constructor */
public MyClass() {}
public Double getValue() {
return value;
}
public void setValue(Double value) {
this.value = value;
}
// The Firebase data mapper will ignore this
@Exclude
public Kind getKindVal() {
return kind;
}
public String getKind() {
// Convert enum to string
if (kind == null) {
return null;
} else {
return kind.name();
}
}
public void setKind(String kindString) {
// Get enum from string
if (kindString == null) {
this.kind = null;
} else {
this.kind = Kind.valueOf(kindString);
}
}
}
回答2:
Just as a side optimizing answer In Android, it is recommended not to use Enums. Use @StringDef or @IntDef, that it could be working without workarounds and you optimized your app for memory.
Very nice video reasoning why: https://www.youtube.com/watch?v=Hzs6OBcvNQE
来源:https://stackoverflow.com/questions/37335712/android-firebase-9-0-0-setvalue-to-serialize-enums