JSON 值无法转换为 System.Collections.Generic.Dictionary`2[System.String,System.String]

问题描述 投票:0回答:1

连载前-

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

我使用 JsonSerializer 将下面的字符串反序列化为一个对象。

string jsonString = JsonSerializer.Serialize(welcomePageConfig);

连载后-

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

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

当我尝试反序列化时,它给我一个错误提示 “无法将 JSON 值转换为 System.Collections.Generic.Dictionary`2[System.String,System.String]。”

在"{"Key...."这部分之后弹出。因为它是字典。

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; }
    }

如何解决这个问题?

c# json json-deserialization jsonserializer json-serialization
1个回答
0
投票

在(反)序列化期间将

Dictionary<string, ...>
作为 JSON 对象处理是一个非常普遍的约定,例如,
System.Text.Json
和 Newtonsoft 的 Json.NET 都支持该约定。似乎在序列化过程中的某个时刻,某些事情没有按预期进行(您没有显示您的序列化代码)并且
Content
的处理方式类似于
IEnumerable
(键值对)而不是
Dictionary
,所以您需要更改反序列化模型:

public class StylingComponent
{
    // ...
    public List<KeyValuePair<string, string>> Content { get; set; }
}
© www.soinside.com 2019 - 2024. All rights reserved.