且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Firebase数据库错误 - 在反序列化时期望映射,但得到了一个类java.util.ArrayList

更新时间:2023-02-18 22:44:35

好的,想通了。如果有人读这个问题有这个问题,并使用递增ints / longs /无论转换为字符串,你必须添加一些字符转换为int。如果可以转换,Firebase显然会将这些键转换回非字符串。



例如,如果你做这样的事情:

  int inc = 0; 
inc ++; // 1
map.put(String.valueOf(inc),someList);

Firebase将此键解释为1而不是1。



因此,强制Fb以字符串的形式解释,像这样做:

  int inc = 0; 
inc ++; // 1
map.put(String.valueOf(inc)+_key,someList);

一切都完美无缺。很显然,如果你还需要把这些字符串读回来,只要把字符串分割成[_]就行了。

Edit: Figured it out, check my posted answer if you're having similar issues.

I know there are several questions about this issue, but none of their solutions are working for me.

In my model class I have made sure to use List instead of Arraylist to avoid Firebase issues, but am still getting this error. It's a lot of code but most questions ask for all the code so I'll post it all.

TemplateModelClass.java

//

I've used this basic model successfully many times. For the

HashMaps<String, List<String>>,

the String is an incremented Integer converted to String. The List's are just Strings in a List. Here's some sample JSON from Firebase:

 //

Formatted that as best as I could. If you need a picture of it let me know and I'll get a screenshot

And am getting this error, as stated in the title:

com.google.firebase.database.DatabaseException: Expected a Map while deserializing, but got a class java.util.ArrayList

The most upvoted question about this seems to have something to do with a problem using an integer as a key, but I think I've avoided that by always using an integer converted to a string. It may be interpreting it strangely, so I'll try some more stuff in the meantime. Thanks for reading!

Alright, figured it out. If anyone reading this has this problem and are using incremented ints/longs/whatever that get converted to strings, you must add some characters to the converted int. Firebase apparently converts these keys back into non-Strings if it can be converted.

For example, if you do something like this:

int inc = 0;
inc++; // 1
map.put(String.valueOf(inc), someList);

Firebase interprets that key as 1 instead of "1".

So, to force Fb to intepret as a string, do something like this:

int inc = 0;
inc++; // 1
map.put(String.valueOf(inc) + "_key", someList);

And everything works out perfectly. Obviously if you also need to read those Strings back to ints, just split the string with "[_]" and you're good to go.