Linq to JSON Sub-query

Jun 15, 2009 at 7:33 PM

Hello again,

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

"{
	short":{
		"original":"http://www.foo.com/",
		"short":"krehqk",
		"error":{
			"code":0,
			"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>();

Coordinator
Jun 16, 2009 at 7:14 AM

Just use indexes.

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

string jsonText = @"{
  ""short"":{
    ""original"":""http://www.foo.com/"",
    ""short"":""krehqk"",
    ""error"":{
      ""code"":0,
      ""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("http://www.foo.com/", 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 10:10 AM

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

Aug 31, 2010 at 2: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\""

 

Coordinator
Aug 31, 2010 at 9: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"];