2

I have this simple json response :

   {
    "results": [
        {
            "address_components": [
                {
                    "long_name": "277",
                    "short_name": "277",
                    "types": [
                        "street_number"
                    ]
                },
                {
                    "long_name": "United States",
                    "short_name": "US",
                    "types": [
                        "country",
                        "political"
                    ]
                },
                {
                    "long_name": "11211",
                    "short_name": "11211",
                    "types": [
                        "postal_code"
                    ]
                }
            ],
            "formatted_address": "277 Bedford Avenue, Brooklyn, NY 11211, USA"
        },
        {
            "a": 2
        }
    ],
    "status": "OK"
}

How can I get the green value according to (yellow) types which contains "country" ?

visualization :

enter image description here

Is it possible to do it via json Linq ? (Newtonsoft.Json.Linq.JObjec)

Something like this psuedo : ( doesn't work/compile)

 JObject jt=   JObject.Parse(dataObjects);
 jt["results"].Where(f=>f.key=="address_components").Where(g=>g["types"].contains("country")).select(h=>h["long_name")

1 Answer 1

7

Yes, that's possible.

jt["results"].Children()
    .Select(t => t["address_components"])
    .Where(a => a != null)
    .Children()
    .Where(c => c["types"].Children().Contains("country"))
    .Select(a => a["long_name"])
    .ToArray();
Sign up to request clarification or add additional context in comments.

4 Comments

Is it ok to say i love you ? :-) I've been dealing with this crappy documentation for 3 hours.
I even went to direction with dynamic and loops.....i.sstatic.net/fUKXy.jpg
f we're here , if I have "United states", how can I get the property name which holds it ? ("long_name" here) - I have done this - but it seems ugly : i.sstatic.net/LOWlW.jpg
I think this is the best way to get it. Another possibility is to use dynamics. You can cast a dynamic object to a Dictionary<string, object> and then you can handle that dictionary. But your solution would be better.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.