简体   繁体   中英

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 (eg [1,2,3]) into type 'System.Collections.Generic.Dictionary 2[System.String,System.Collections.Generic.List 1[System.String]]' because the type requires a JSON object (eg {"name":"value"}) to deserialize correctly.
To fix this error either change the JSON to a JSON object (eg {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (eg 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 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);

JSON syntax for dictionary is { "key1": "val1", "key2: "val2".....}

So if your JSON is structured as follows, your conversion will work as it is.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM