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

JsonSerializer反序列化Dictionary类型报错的解决方法咨询

解决System.Text.Json反序列化Dictionary时的类型转换错误

问题背景

使用JsonSerializer.Serialize()序列化WelcomePageConfig对象后,原本为键值对对象形式的content字段被序列化为键值对数组:

{"WelcomeTitleText":{"Style":{"Color":"#FFFFFF"},"Content":[{"Key":"sv","Value":"Välkommen"},{"Key":"en","Value":"Welcome"}]}}

反序列化时出现错误:"The JSON value could not be converted to System.Collections.Generic.Dictionary2[System.String,System.String]"`,实体类定义如下:

public class WelcomePageConfig
{
    [JsonProperty("welcomeTitleText")]
    public StylingComponent WelcomeTitleText { get; set; }
}

public class StylingComponent
{
    [JsonProperty("style")]
    public Style Style { get; set; }

    [JsonProperty("content")]
    public Dictionary<string, string> Content { get; set; }
}

public class Style
{
    [JsonProperty("color")]
    public string Color { get; set; }
}

解决方案

方案1:自定义JsonConverter处理数组与Dictionary的转换

创建自定义转换器,实现键值对数组与Dictionary<string, string>的双向转换:

public class DictionaryConverter : JsonConverter<Dictionary<string, string>>
{
    public override Dictionary<string, string> Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        var keyValuePairs = JsonSerializer.Deserialize<KeyValuePair<string, string>[]>(ref reader, options);
        return keyValuePairs?.ToDictionary(kvp => kvp.Key, kvp => kvp.Value) ?? new Dictionary<string, string>();
    }

    public override void Write(Utf8JsonWriter writer, Dictionary<string, string> value, JsonSerializerOptions options)
    {
        JsonSerializer.Serialize(writer, value.ToArray(), options);
    }
}

在实体类的Content属性上标记该转换器:

public class StylingComponent
{
    [JsonProperty("style")]
    public Style Style { get; set; }

    [JsonProperty("content")]
    [JsonConverter(typeof(DictionaryConverter))]
    public Dictionary<string, string> Content { get; set; }
}

之后执行反序列化即可正常解析:

welcomePageConfig = JsonSerializer.Deserialize<WelcomePageConfig>(jsonString);

方案2:修改序列化配置,让Dictionary保持键值对对象形式

如果不需要将Dictionary序列化为数组,可指定序列化配置,强制将Dictionary输出为JSON对象:

var options = new JsonSerializerOptions
{
    DictionaryKeyPolicy = JsonNamingPolicy.CamelCase,
    WriteIndented = true
};
string jsonString = JsonSerializer.Serialize(welcomePageConfig, options);

序列化后的content字段会保持为键值对对象格式:

{
  "welcomeTitleText": {
    "style": {
      "color": "#FFFFFF"
    },
    "content": {
      "sv": "Välkommen",
      "en": "Welcome"
    }
  }
}

后续使用默认配置反序列化即可正常转换。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 13:20:13