You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#从Firebase Database读取类内字典时Json反序列化异常如何解决

问题根因

报错的核心原因是:当Firebase Realtime Database检测到节点下的子键为连续数字字符串时,会自动将该结构转换为JSON数组返回,而C#的Dictionary<uint, bool>要求反序列化的源必须是JSON对象(键值对结构),两者格式不匹配导致反序列化失败。

可行解决方案

方案1:调整存储逻辑,强制保留JSON对象结构

无需修改原有UserProfile类定义,仅修改存数据的规则,避免Firebase自动转数组:

  • 给数字键添加固定非数字前缀,比如加前缀k_,破坏Firebase的连续数字识别逻辑:
// 存储时代码调整为
firebaseClient.Child("users").Child(id + "").Child("dictionary").Child($"k_{value}").PutAsync(true);
  • 配套给dictionary字段添加序列化键转换逻辑,反序列化时自动去除前缀、序列化时自动添加前缀即可。

方案2:修改接收类型适配数组结构

如果不想调整存储逻辑,可修改UserProfile的字段类型适配返回的数组,再自行转换为字典:

public class UserProfile
{
    // 用List接收Firebase返回的数组
    public List<bool> dictionary = new List<bool>();
    // 扩展属性转换为业务需要的字典
    public Dictionary<uint, bool> ConvertedDictionary
    {
        get
        {
            var result = new Dictionary<uint, bool>();
            for (uint i = 0; i < dictionary.Count; i++)
            {
                result.Add(i, dictionary[(int)i]);
            }
            return result;
        }
    }
    // 其他变量
}

注意:该方案仅适用于字典键是从0开始的连续整数的场景,非连续键会出现数据丢失。

方案3:自定义JSON转换器

如果要同时保留原有存储逻辑和Dictionary类型定义,可自定义JSON转换器适配数组转字典的逻辑,以Newtonsoft.Json为例:

  1. 实现自定义转换器:
public class ArrayToDictConverter : JsonConverter<Dictionary<uint, bool>>
{
    public override Dictionary<uint, bool> ReadJson(JsonReader reader, Type objectType, Dictionary<uint, bool> existingValue, bool hasExistingValue, JsonSerializer serializer)
    {
        var dict = new Dictionary<uint, bool>();
        var array = JArray.Load(reader);
        for (uint i = 0; i < array.Count; i++)
        {
            dict.Add(i, array[i].Value<bool>());
        }
        return dict;
    }

    public override void WriteJson(JsonWriter writer, Dictionary<uint, bool> value, JsonSerializer serializer)
    {
        serializer.Serialize(writer, value);
    }
}
  1. 给字段绑定转换器:
public class UserProfile
{
    [JsonConverter(typeof(ArrayToDictConverter))]
    public Dictionary<uint, bool> dictionary = new Dictionary<uint, bool>();
    // 其他变量
}

内容的提问来源于stack exchange,提问作者itsnottme

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.11 17:57:00