Reputation: 2513
I am trying to deserialize this JSON string to different objects in C# using Newtonsoft.Json
{"apple":{"title":"apple","color":"red"},"banana":{"title":"banana","color":"yellow"}}
Note "apple" and "banana" in this example are dynamic values, so it's very well possible that suddenly it's called something others, e.g. ananas.
Now what I'm trying to do is deserialize this JSON string in a way that I can do a foreach loop through all the objects (Apple, Banana, ...) to read the value of the color
field.
But apparently I'm doing something wrong, this is my code.
dynamic d = JObject.Parse(jsonString);
foreach (dynamic e in d)
{
Console.WriteLine(e.title);
}
Does anyone know why this does not work like this?
Upvotes: 0
Views: 111
Reputation: 21568
e
is a KeyValuePair<String,JToken>
so we need to access e.Value
to get the title
.
var d = JObject.Parse(@"{""apple"":{""title"":""apple"",""color"":""red""},""banana"":{""title"":""banana"",""color"":""yellow""}}");
foreach (dynamic e in d)
{
Console.WriteLine(e.Value.title);
}
Upvotes: 1
Reputation: 124
Try using System.Web.Script.Serialization
then doing the following:
var jss = new JavaScriptSerializer();
var dict = jss.Deserialize<Dictionary<string, dynamic>>(YOURJSON);
To use this do:
string item = dict["name"];
string itema = dict["item"]["thing"];
Hope this helps.
Upvotes: 0