我正在使用Google的Firebase。我将Java Enum作为其中一个模型类的成员之一。将实例保存到Firebase数据库时,会引发异常。解决的最佳方法是什么?
答案 0 :(得分:2)
经过进一步研究。以下是Firebase 3.0.0的解决方法。显然以前的版本Firebase对已被淘汰的Jackson有更灵活的支持。这是一个带有枚举的Job类(使用hacky代码)
public class Job {
public enum JobLifecycle {
New, inTransit, inStorage, delivered, signedOff;
}
...// other fields omitted
JobLifecycle lifecycle;
public Job(){
}
@Exclude
public JobLifecycle getLifecycleAsEnum(){
return lifecycle;
}
// these methods are just a Firebase 9.0.0 hack to handle the enum
public String getLifecycle(){
if (lifecycle == null){
return null;
} else {
return lifecycle.name();
}
}
public void setLifecycle(String lifecycleString){
if (lifecycleString == null){
lifecycle = null;
} else {
this.lifecycle = JobLifecycle.valueOf(lifecycleString);
}
}
}
答案 1 :(得分:1)
找到了我的问题的部分答案,但仍在寻找解决方法。
如果定义了如下所示的枚举和模型类,那么突然枚举将成功保存为2节点结构,其中typename为父节点,枚举字符串值为子节点。但是,当我尝试使用Job j = xxx.getValue(Job.class)
之类的代码读取节点时会抛出异常:com.google.firebase.database.DatabaseException: Class com.ranchosoftware.ranchomovingandstorage.model.JobLifecycle is missing a constructor.
根据Frank的评论,我认为Firebase中没有解决方案现在。我不确定什么是最好的解决方法。
public enum JobLifecycle {
New, inTransit, inStorage, delivered, signedOff;
JobLifecycle(){}
String value;
@JsonValue
public String getValue(){
return this.name();
}
@JsonCreator
public static JobLifecycle fromValue(String jobLifecycleString){
for (JobLifecycle l : JobLifecycle.values()){
if (l.name().equals(jobLifecycleString)){
return l;
}
}
throw new IllegalArgumentException("Invalid jobLifecycle code: " + jobLifecycleString);
}
}
在模型类中使用它:
public class Job {
... // other fields omitted
JobLifecycle lifecycle;
public Job(){
}
... // other content omitted
@JsonProperty("lifecycle")
public JobLifecycle getLifecycle(){
return lifecycle;
}
}