This project has moved and is read-only. For the latest updates, please go here.

Linq to JSON Sub-query

Jun 15, 2009 at 8:33 PM

Hello again,

New to Linq as well as Json. Given the json object:

			"msg":"No action taken"}

How do select the sub item error.

So far I have the following, but its giving me a "Cannot access child value on Newtonsoft.Json.Linq.JProperty" - what am I doing wrong?


// r is the string containing the above json object.
JObject json = JObject.Parse(r); Shortie shortie = (from child in json["short"].Children() select new Shortie { Original = child.Value<String>("original"), Short = child.Value<String>("short"), Error = (from err in json["children"]["error"].Children() select new ShortieException { Code = err.Value<int>("code"), ErrorMessage = err.Value<String>("msg") }).Single<ShortieException>() }).Single<Shortie>();

Jun 16, 2009 at 8:14 AM

Just use indexes.

I need to add more documentation. Do you mind if I use this as an example?

string jsonText = @"{
      ""msg"":""No action taken""}

JObject json = JObject.Parse(jsonText);

Shortie shortie = new Shortie
                    Original = (string)json["short"]["original"],
                    Short = (string)json["short"]["short"],
                    Error = new ShortieException
                              Code = (int)json["short"]["error"]["code"],
                              ErrorMessage = (string)json["short"]["error"]["msg"]

Assert.AreEqual("", shortie.Original);
Assert.AreEqual("krehqk", shortie.Short);
Assert.AreEqual(null, shortie.Shortened);
Assert.AreEqual(0, shortie.Error.Code);
Assert.AreEqual("No action taken", shortie.Error.ErrorMessage);

Jun 16, 2009 at 11:10 AM

I knew it would be something easy, thanks again James.

Aug 31, 2010 at 3:57 PM

Whenever I use JObject.Parse() all of my strings (at least in sub properties) are wrapped in escaped double quotes:

Simple example: var responseJson = "{Status:{Result:'Success', Message:'All good'}}";

When I try to access the properties like this I get above issue:

JObject jObject = JObject.Parse(responseJson);
JObject status = JObject.Parse(jObject["Status"].ToString());

// If I do this:   status["Result"].ToString() OR jObject["Status"]["Result"].ToString() I always get this: "\"Success\""


Aug 31, 2010 at 10:44 PM

ToString() outputs the value as it would be written in JSON, which for strings includes quotes. To get the actual value cast the value to string:

string result = (string)status["Result"];