0

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?

Stephen Kennedy
  • 20,585
  • 22
  • 95
  • 108
Kaj
  • 2,445
  • 3
  • 23
  • 34
  • I haven't used this module in a while but is there a reason why the solution in this thread http://stackoverflow.com/questions/4749639/deserializing-json-to-net-object-using-newtonsoft-or-linq-to-json-maybe doesn't work? Also, what error are you getting? – bbill Jul 09 '15 at 15:24

3 Answers3

4

You want to do e.Value.title instead of just e.title.

DotNetFiddle example here.

Inspector Squirrel
  • 2,548
  • 2
  • 27
  • 38
Brant Olsen
  • 5,628
  • 5
  • 36
  • 53
1

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);
}
Stephen Kennedy
  • 20,585
  • 22
  • 95
  • 108
0

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.

Aidon Hudson
  • 124
  • 8