简体   繁体   中英

LINQ - JSON Help needed

I am having trouble writing the proper LINQ syntax. I have used it before but never to a JSON file.I have created the following code by searching and experimenting with examples found here and other sites. I think I am close but can't seem to figure it out. I am using vs2010 C# targeting .net 4 with references to Newtonsoft.Json and Newtonsoft.Json.Linq.

I need to be able to get the from.number and the body from this file.

{ "message": { "to": { "num": "7891234567", "name": "Jane Doe" }, "body": "Hello", "from": { "num": "1231234567", "name": "John Doe" }, "type": 0, "dateTime": 1301493974000 } }

        var jObj = JObject.Parse(jFile);

        var pNum = from msg in jObj["message"]["from"].Children()                       
                   select (string)msg; 

        foreach(var n in pNum)
        {
            Console.WriteLine(n);
        }

The above code does print from.num values and the from.name values. I am looking for just the num value, not both. I am not quite sure how to isolate the value that I want.

I have tried......

       select (string)msg["num"];

Without success. I get an error "Cannot access child value on Newtonsoft.Json.Linq.JProperty." I also need a query to get the body value.

Thanks, Jeff

This should work:

string json = "{ \"message\": { \"to\": { \"num\": \"7891234567\", \"name\": \"Jane Doe\" }, \"body\": \"Hello\", \"from\": { \"num\": \"1231234567\", \"name\": \"John Doe\" }, \"type\": 0, \"dateTime\": 1301493974000 } }";

JavaScriptSerializer js = new JavaScriptSerializer();
dynamic foo = js.Deserialize<dynamic>(json);
var message = new {Num = foo["message"]["from"]["num"], Body = foo["message"]["body"]};

Console.WriteLine("{0}: {1}", message.Num, message.Body);
Console.ReadLine();

For future reference I should have added that the JavaScriptSerializer is in the System.Web.Extensions assembly.

Don't have the setup to try this myself, looking at the documentation I came up with this. Can you try and see if the following works?

var pNum = from msg in jObj["message"]["from"]
               select (string)msg.SelectToken("num"); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM