尝试从Firebase Database c#加载类内的字典时出现JSON异常



让我们考虑一个具有字典的类

public class UserProfile
{
public Dictionary<uint, bool> dictionary = new Dictionary<uint, bool>();
//other variables
}

然后,我将字典中的一个新字段添加到数据库中:

firebaseClient.Child("users").Child(id + "").Child("dictionary").Child(value + "").PutAsync(true);

当我尝试从数据库中读取类时(该类以前已经添加过(:

UserProfile userProfile = await firebaseClient.Child("users").Child(id + "").OnceSingleAsync<UserProfile>()

我从Json反序列化中得到一个错误。

JsonSerializationException: Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'System.Collections.Generic.Dictionary`2[System.UInt32,System.Boolean]' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List<T> that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.
Path 'dictionary', line 1, position 147.

我需要使用什么格式才能正确地取消验证?

错误消息为(emphasis mine(:

JsonSerializationException:无法将当前JSON数组(例如[1,2,3](反序列化为类型"System"。集合。通用的字典"2[System.UInt32,System.Boolean]",因为该类型需要JSON对象(例如{"name":"value"}(才能正确反序列化

要修复此错误,请将JSON更改为JSON对象(例如{"name":"value"}(,或者将反序列化的类型更改为数组或实现集合接口(例如ICollection、IList(的类型,如可以从JSON数组反序列化的List。JsonArrayAttribute也可以添加到类型中,以强制它从JSON数组反序列化。

路径"dictionary",第1行,位置147。

所以:您正试图将JSON中的数组转换为C#中的Dictionary,如果不为其编写额外的代码,这是不可行的。

我的猜测是,您的id值是连续的数值,Firebase将其解释为数组索引。因此,当您尝试读回数据时,您会得到一个数组,但您的代码需要一个对象。

如果这确实是原因,最简单的解决方法是而不是只使用数字作为密钥,而是在它们前面加一个短的字母数字值,如下所示:

firebaseClient.Child("users").Child("key_"+id).Child("dictionary").Child(value + "").PutAsync(true);
//                                   👆 change here

通过此更改,键都是字母数字,Firebase将不再将它们解释为数组,您的代码将获得所需的Dictionary


更新:或者,您可以不修改数据结构,但在这种情况下,您的数据结构需要是一个数组或List,正如错误消息的后半部分所说。

最新更新