Adil Waqar Adil Waqar - 2 months ago 9
C# Question

How I can deserialize Json into Dictionary<String,List<String>>

I have a sample Json

[{"_2":["HR Data","Reformed (Master File)"]}]


and I am trying to deserialize it into below model

public class ExploreCriteria
{
public Dictionary<String, List<String>> Explore { get; set; }
}


this is what I have tried so far

ExploreCriteria Explore = new ExploreCriteria();
Explore = JsonConvert.DeserializeObject<ExploreCriteria>(JsonStr);


but it says

Cannot deserialize the current JSON array (e.g. [1,2,3]) into type
'DataModels.ExploreCriteria' because the type requires a JSON object
(e.g. {"name":"value"}) to deserialize correctly.

Answer

The provided JSON and your ExploreCriteria class do not describe the same structure.

Your JSON structure is an array that contains a key with an array value. So you can either remove the square brackets to

{"_2":["HR Data","Reformed (Master File)"]}

then your ExploreCriteria is fitting. Or you can change the JsonConvert call to

var JsonStr = "[{\"_2\":[\"HR Data\",\"Reformed(Master File)\"]}]";
ExploreCriteria Explore = new ExploreCriteria();
var data = JsonConvert.DeserializeObject<IEnumerable<Dictionary<String, List<string>>>>(JsonStr);
Explore.Explore = data.FirstOrDefault();
Comments