简体   繁体   English

反序列化时需要一个列表,但得到了一个类 java.util.HashMap

[英]Expected a List while deserializing, but got a class java.util.HashMap

I'm trying to get a list of users from Firebase, in Android.我正在尝试从 Android 中的 Firebase 获取用户列表。

在此处输入图像描述

I already have the uuid of the user, and using that I'm trying to get the entire object.我已经有了用户的 uuid,并使用它来尝试获取整个对象。 The uuid is both the node name and a field inside the user node (identical, of course). uuid 既是节点名又是用户节点内的字段(当然是一样的)。

Here is my code:这是我的代码:

DatabaseReference usersRef = FirebaseDatabase.getInstance().getReference("users");
Query query = usersRef.orderByChild("uuid").equalTo(animalMarker.getUserUid());
    query.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            Log.d(TAG, "onDataChange: xxxxxxxx---- entered onDataChange");

            // go to node "users/userUID" , becuase dataSnapshot is parent node
            for (DataSnapshot ds : dataSnapshot.getChildren()) {
                Log.d(TAG, "xxxxxxxx---- onDataChange: ds= " + ds);
                User user = ds.getValue(User.class);
                Log.d(TAG, "xxxxxxxx---- onDataChange: user=" + user);
                // createdByTV.setText("Created by \n" + user.getEmail());
            }

        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });

I dont know if the error "expected List but got HashMap" is coming from the entire DataSnapshot itself, or from the animals List inside the user ( The user class has a field List animals )我不知道错误“expected List but got HashMap”是来自整个 DataSnapshot 本身,还是来自用户内部的动物列表(用户类有一个字段 List animals)

I've already checked this similar question Andorid-Expected a List while deserializing, but got a class java.util.HashMap and several others but I still can't understand what is wrong.我已经检查了这个类似的问题Andorid-Expected a List while deserializing,但是得到了一个类 java.util.HashMap和其他几个,但我仍然不明白哪里出了问题。

EDIT: I'm trying to get the user email, knowing it's ID(uuid).编辑:我正在尝试获取用户电子邮件,知道它的 ID(uuid)。 While getting the entire User object is not necessary, I'm curios as to how it would be done, since I can't manage to do either of these.虽然获取整个 User 对象不是必需的,但我很好奇它是如何完成的,因为我无法做到其中任何一个。

EDIT: here is my User class编辑:这是我的用户类

public class User {

private String uuid;
private String email;
private String name;
private List<User> friends;
private List<Animal> animals;

public User() {
}

public User(String email, String name) {
    this.email = email;
    this.name = name;
}

public User(String uuid, String email, String name) {
    this.uuid = uuid;
    this.email = email;
    this.name = name;
}
... // getters and setters, toString and other such
}

When trying to get the User which doesn't have the animals node inside it, everything works fine.当试图获取其中没有动物节点的用户时,一切正常。 but when trying to get the user with the animals node inside, the app crashes.但是当试图让用户在里面有动物节点时,应用程序崩溃了。

Actually, I answered that question but in this case the problem is a little different.实际上,我回答了那个问题,但在这种情况下,问题有点不同。 So you are getting the following error:所以你收到以下错误:

expected List but got HashMap预期列表但得到 HashMap

Because your animals node that exist within each user object is not a list of animal objects is actually a map of animal objects and that's why this error.因为存在于每个用户对象中的animals节点不是动物对象列表,实际上是动物对象的地图,这就是出现此错误的原因。

While getting the entire User object is not necessary, I'm curios as to how it would be done, since I can't manage to do either of these.虽然获取整个 User 对象不是必需的,但我很好奇它是如何完成的,因为我无法做到其中任何一个。

It's true, you can get the email address simply using the following line of code:没错,您只需使用以下代码行即可获取电子邮件地址:

String email = ds.child("email").getValue(String.class);

Now, to map a DataSnapshot object to a User and get a list of animal objects from a particular user, please remove:现在,要将DataSnapshot对象映射到User并从特定用户获取动物对象列表,请删除:

//private List<User> friends;
//private List<Animal> animals;

And use the following lines of code:并使用以下代码行:

String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference animalsRef = rootRef.child("users").child(uid).child("animals");
ValueEventListener valueEventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        List<Animal> animalList = new ArrayList<>();
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            Animal animal = ds.getValue(Animal.class);
            animalList.add(animal);
        }

        //Do what you need to do with the animalList
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {
        Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
    }
};
animalsRef.addListenerForSingleValueEvent(valueEventListener);

The animals list is not inside the user, it is inside the users node.动物列表不在用户内部,而是在用户节点内部。 In any case making it inner to the user object seems to be more nested than needed.在任何情况下,将其置于用户对象内部似乎比需要的嵌套更多。 You should have another node for the animals你应该有另一个节点的动物

user_animals:{
    uid:{key1:{}, key2:{}
}

Your problem now is you are making a query instead of getting the node value您现在的问题是您正在查询而不是获取节点值

usersRef.child(uid).addSingleEvent..

...onDataChange...
User user = datasnapshot.getValue(User.class);

You need to create a User class that reflects your users attributes in the RTD您需要创建一个用户类来反映 RTD 中的用户属性

The way you build your tree is the root of the problem.构建树的方式是问题的根源。

I had the same error just today while refactoring a firebase tree of an old project, so I looked for the error in google and found this page, and I notice this 3 user attributes inside your animal node that looked out of place.就在今天,我在重构一个旧项目的 firebase 树时遇到了同样的错误,所以我在谷歌中查找错误并找到了这个页面,我注意到你的动物节点中的这 3 个用户属性看起来不合适。

So I went back to my tree and apprantly I had mistakenly added a key:value pair inside one of my list nodes, so I removed them and everything was fine.所以我回到我的树,显然我在我的一个列表节点中错误地添加了一个键:值对,所以我删除了它们,一切都很好。

The problem:问题:

It is because you have a list of animals and inside that list you have this 3 key-values (email, uuid, name), this confuses firebase serilization so he tries to convert it into hashmap这是因为您有一个动物列表,并且在该列表中您有这 3 个键值(电子邮件、uuid、名称),这会混淆 firebase serilization,因此他试图将其转换为 hashmap

The solution:解决方案:

I think you will benefit in the future if you don't work around it and do as follows: the 3 user attributes email, name and uuid should be wrapped inside a different node inside the user tree, something like user_data and you should have a different node for animals that will have only the animal list!我认为如果您不解决它并按照以下方式操作,您将来会受益:3 个用户属性 email、name 和 uuid 应该包装在用户树内的不同节点中,比如 user_data 并且你应该有一个动物的不同节点将只有动物列表!

  • users用户
    • sfdasfasfasfasf sfdasfasfasfasf
      • user_data用户数据
        • email:"asdf"电子邮件:“asdf”
        • name:"asdfas"名称:“asdfas”
        • uuid:"dfqwtr4" uuid:“dfqwtr4”
      • animals动物
        • asdfaskdfjlasdgafd asdfaskdfjlasdgafd
          • adult:"asdf"成人:“asdf”
          • animalId:"asdfas"动物编号:“asdfas”
          • animalName:"dfqwtr动物名称:“dfqwtr
          • approxAge:"asdf"大约年龄:“asdf”
          • neutred:"asdfas"中性:“asdfas”
          • photoLink:"dfqwtr"图片链接:“dfqwtr”
        • sdafasfdasgasga sdafasfdasgasga
          • adult:"asdf"成人:“asdf”
          • animalId:"asdfas"动物编号:“asdfas”
          • animalName:"dfqwtr动物名称:“dfqwtr
          • approxAge:"asdf"大约年龄:“asdf”
          • neutred:"asdfas"中性:“asdfas”
          • photoLink:"dfqwtr"图片链接:“dfqwtr”

Then your pojo's should look something like: a User class with properties of a UserData and List<Animal> with the corresponding names for serilization.然后你的 pojo 应该看起来像:一个User类,具有UserDataList<Animal>的属性,具有相应的序列化名称。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Firebase 错误:“反序列化时需要一个列表,但得到一个 class java.util.HashMap” - Firebase Error: "Expected a List while deserializing, but got a class java.util.HashMap" Firebase“无法将 java.util.HashMap 类型的值转换为 int” - Firebase "Failed to convert a value of type java.util.HashMap to int" 当我尝试从 firebase 检索数据到 viewpager2 时,无法将 java.util.HashMap 类型的值转换为字符串错误 - Failed to convert value of type java.util.HashMap to String error when I'm trying to retrieve data from firebase to viewpager2 Pandas to_gbq() TypeError "Expected bytes, got a 'int' object - Pandas to_gbq() TypeError "Expected bytes, got a 'int' object 语法错误:应为“(”或“,”或关键字 SELECT 但脚本结束 - Syntax error: Expected "(" or "," or keyword SELECT but got end of script Gcloud PubSub Java 实现 - java.util.concurrent.RejectedExecutionException - Gcloud PubSub Java implementation - java.util.concurrent.RejectedExecutionException 无效的道具:道具“chartData”的类型检查失败。 预期 Object,得到 Null vue.js - Invalid prop: type check failed for prop "chartData". Expected Object, got Null vue.js 使用 StreamBuilder 和 bool 实时更新 UI -ERROR 预期类型为“地图”的值<dynamic, dynamic> ',但得到了“_JsonDocumentSnapshot”类型之一</dynamic,> - Realtime Update of UI with StreamBuilder and bool -ERROR Expected a value of type 'Map<dynamic, dynamic>', but got one of type '_JsonDocumentSnapshot' pandas.to_gbq() 返回“ArrowTypeError: Expected bytes, got a 'datetime.date' object”错误 - pandas.to_gbq() returning "ArrowTypeError: Expected bytes, got a 'datetime.date' object" error 使用 with 子句时出错我收到消息“语法错误:预期的关键字 AS 但在 [7:14] 得到了“(” - Error using the with clause I received message " Syntax error: Expected keyword AS but got "(" at [7:14]"
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM