Search code examples
c#jsondictionaryjson.net

Trying to deserialize JSON into Dictionary<string, List<string>> in c#


I'm trying to deserialize JSON into a dictionary with strings as keys and lists of strings as values. The way I did it is this:

[
    {
        "key1": [
            "value1.1",
            "value1.2"
        ]
    },
    {
        "key2": [
            "value2.1",
            "value2.2"
        ]
    },
]

and to deserialize:

Dictionary<string, List<string>> dictionary;
string text = File.ReadAllText(@"Text.json");
dictionary = JsonConvert.DeserializeObject<Dictionary<string, List<string>>>(text);

I am receiving the errors:

Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'System.Collections.Generic.Dictionary2[System.String,System.Collections.Generic.List1[System.String]]' 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 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 '', line 1, position 1.'

Does anyone have have any insights for me?


Solution

  • Solution As Per Question:

    Try this, Hopefully this will help you. https://dotnetfiddle.net/f3u1TC

    string json = @"[{""key1"":[""value1.1"",""value1.2""]},{""key2"":[""value2.1"",""value2.2""]}]";
    var dictionary = JsonConvert.DeserializeObject<Dictionary<string, List<string>>[]>(json);
    

    Edit

    Updated Solution:

    If you don't need an array. Then you have to update your json. Remove array braces [] and add these ones {}

    Json

    {
        {
            "key1": [
                "value1.1",
                "value1.2"
            ]
        },
        {
            "key2": [
                "value2.1",
                "value2.2"
            ]
        },
    }
    

    C#

    string json = @"{""key1"":[""value1.1"",""value1.2""],""key2"":[""value2.1"",""value2.2""]}";
    var dictionary = JsonConvert.DeserializeObject<Dictionary<string, List<string>>>(json);