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?

1
  • I haven't used this module in a while but is there a reason why the solution in this thread stackoverflow.com/questions/4749639/… doesn't work? Also, what error are you getting? Commented Jul 9, 2015 at 15:24

3 Answers 3

4

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

DotNetFiddle example here.

Sign up to request clarification or add additional context in comments.

Comments

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);
}

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.