Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
730 views
in Technique[技术] by (71.8m points)

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?

question from:https://stackoverflow.com/questions/65559999/trying-to-deserialize-json-into-dictionarystring-liststring-in-c-sharp

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...