I’m trying to deserialize a JSON response in c# using Newtonsoft.Json
Here is an example of the type of JSON response I’m working with:
{
"version": "1.0",
"fixes": [
{
"fix1": "this is fix 1",
"fix2": "this is fix 2",
"fix3": "this is fix 3"
}
]
}
In this response there can be any number of "fixes."
My object class looks like this:
public class Update
{
public class Fix
{
public IDictionary<string, string> Values { get; set; }
}
public class Root
{
public string version { get; set; }
public List<Fix> fixes { get; set; }
}
}
Here I’m deserializing the http response and trying to get value of fixes, but all of the values are null:
var root = JsonConvert.DeserializeObject<Update.Root>(strContent);
Update.Fix fixes = root.fixes[0];
foreach (var fix in fixes.Values)
{
string test = fix.Value.ToString();
}
2
Answers
your fixes are a dictionary, not a collection, but you can convert it to a collecton
output
or dictionary
output
Eliminate the class
Fix
. InRoot
havepublic List<Dictionary<string, string>> fixes { get; set; }
:Then, to loop through all the keys and values, you can use
SelectMany()
to project the list of dictionaries to an enumerable of key/value pairs:Demo fiddle here.