markzzz
markzzz

Reputation: 47965

Selecting node with JSON.NET & LINQ

I get this JSON (I wrote it as XML):

<statuses>
    <metadata>
        <result_type>recent</result_type>
        <iso_language_code>tl</iso_language_code>
    </metadata>
    <created_at>Tue Jul 16 07:56:04 +0000 2013</created_at>
    <user>
        <id>1234</id>
        <id_str>4567</id_str>
        <name>Marco</name>      
    </user>
</statuses> 

(this is how it looks):

{
    "statuses":[
    {
        "metadata":{
            "result_type":"recent",
            "iso_language_code":"tl"
        },
        "created_at":"Tue Jul 16 07:56:04 +0000 2013",
        "user":{
            "id":366581342,
            "id_str":"366581342",
            "name":"Marco Dalla Piazza"
        }
    }]
}       

and I want to extract the fields created_at and name (under user).
How can I do it using JSON.NET library and LINQ?

Tried (for the name):

JObject xDoc = JObject.Parse(objectText);
var leo = xDoc.Descendants("user").Select(n => new
    name = n.Element("name").Value
{
}).First(); 

but seems that I don't have that LINQ methods (as I have in LINQ to XML).

Upvotes: 1

Views: 2328

Answers (1)

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174329

You should be able to use LINQ to JSON for this task:

JObject o = JObject.Parse(objectText);
var result =
    o["statuses"].Select(x => new { CreatedAt = (DateTime)x["created_at"],
                                    Name = (string)x["user"]["name"] });

Upvotes: 2

Related Questions