开发者

LINQ - JSON Help needed

开发者 https://www.devze.com 2023-02-21 03:03 出处:网络
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 s

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开发者_JAVA技巧 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"); 
0

精彩评论

暂无评论...
验证码 换一张
取 消