Kaj
Kaj

Reputation: 2513

Deserialize JSON using C#

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

Answers (3)

Stephen Kennedy
Stephen Kennedy

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

Brant Olsen
Brant Olsen

Reputation: 5664

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

DotNetFiddle example here.

Upvotes: 4

Aidon Hudson
Aidon Hudson

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

Related Questions