Search code examples
c#jsonjson-deserializationjsonserializerjson-serialization

The JSON value could not be converted to System.Collections.Generic.Dictionary`2[System.String,System.String]


Before serialize -

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

I use JsonSerializer to deserialize below string to an object.

string jsonString = JsonSerializer.Serialize(welcomePageConfig);

After serialize -

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

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

When I try to deserialize, it gives me an error mentioning "The JSON value could not be converted to System.Collections.Generic.Dictionary`2[System.String,System.String]."

It pops after "{"Key...." this part. Since it's a dictionary.

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

How to fix this issue?


Solution

  • There is quite a common convention that Dictionary<string, ...> is handled as JSON object during (de)serialization, this convention for example is supported by both System.Text.Json and Newtonsoft's Json.NET. It seems that at some point during serialization something is going not as expected (you have not shown your serialization code) and the Content is handled like IEnumerable (of key-value pairs) not as Dictionary, so you need to change the model for deserialization:

    public class StylingComponent
    {
        // ...
        public List<KeyValuePair<string, string>> Content { get; set; }
    }