错误Firebase在反序列化时期望列表,但得到了一个类java.util.HashMap

时间:2017-04-23 17:14:16

标签: android firebase firebase-realtime-database

我知道这个错误很受欢迎,我在这里阅读很多,但我仍然不确定什么对我来说最好:

所以我有服务类(POJO)及其结构:

public class Service{


private long priceShort;
private String name;
private String desc;
List<String> employees = new ArrayList<>();  //recently added


public Service() {  //default constructor

}

public Service(String name, String desc, long priceShort,ArrayList<String> employees ) {
    this.name = name;
    this.desc = desc;
    this.priceShort = priceShort;
    this.employees = employees;  //recently added
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getDesc() {
    return desc;
}

public void setDesc(String desc) {
    this.desc = desc;
}

public long getPriceShort() {
    return priceShort;
}

public void setPriceShort(long priceShort) {
    this.priceShort = priceShort;
}


public List<String> getEmployees() {
    return employees;
}
public void setEmployees(List<String> employess) {
    this.employees = employees;
}

}

db结构:

"sid1" : {  
  "name" : "Read",
  "desc" : "",
  "priceShort" : 1000,     
   "employees" : {  //recently added
    "John" : "true",
    "David" : "true",
    "Mike" : "true"
  }
},
"sid2" : {
  "name" : "Write",
  "desc" : "xxx",    
  "priceShort" : 2000,
   "employees" : {
    "David" : "true"
  }
}
valueListener中出现

错误,这是我的代码:

 private void listenServiceAll() {

    List<Service> serviceList = new ArrayList<Service>();
    mDatabase.child("ServicesPrice").addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {


            serviceList.clear();
            for (DataSnapshot dsp : dataSnapshot.getChildren()) {
                serviceList.add(dsp.getValue(Service.class)); //add result into array list
            }


            reservationServiceAdapter.notifyDataSetChanged();

            // ...
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            // ...
        }


    });
}

如何解决这个问题?

注意:我之前没有错误,一切运行良好,直到我决定更改我的结构并在我的服务类中添加员工列表List<String> employees = new ArrayList<>;

但我添加的原因是能够根据我的结构保存值(嵌套员工,我想指定每个服务都可以由特定员工完成)

更新

在检查弗兰克爵士的链接后,我将List<String> employees = new ArrayList<>();更改为 Map<String, Object> employees = new HashMap<String, Object>();

使用setter和getter:

 public void setValue(Map<String, Object> map)
{
    this.employees = map;
}
public Map<String, Object> getValue()
{
    return this.employees;
}

但是再次运行调试后,错误消失但我无法将员工值设置到我的对象中。 (虽然我可以看到数据快照实际上有值)。

更新2: 我实际上能够通过迭代孩子来获得价值..

 if (dsp.child("employees").getValue() != null) {
                    for (DataSnapshot emp : dsp.child("employees").getChildren()) {
                        listOfEmployee.add(emp.getKey());
                    }

                }

我可以继续这样做,但我想知道为什么即使在将hashmap添加到我的服务类之后,我也可以通过serviceList.add(dsp.getValue(Service.class));直接获得该值。

0 个答案:

没有答案