2014-11-03 68 views
2

我有這個簡單的JSON響應:通過json.net中的屬性名稱查找值?

{ 
    "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" 
} 

如何可以根據(黃色)types包含"country"我得到的綠色價值?

可視化:

enter image description here

是否有可能通過JSON的LINQ辦呢? (Newtonsoft.Json.Linq.JObjec)

像這樣的事情:(不起作用/編譯)

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

回答

5

是的,這是可能的。

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(); 
+0

可以說我愛你嗎? :-)我一直在處理這個蹩腳的文檔3個小時。 – 2014-11-03 13:01:15

+0

哈哈..一個upvote就足夠了;-) – MichaelS 2014-11-03 13:02:22

+0

我甚至去動態和循環的方向..... http://i.stack.imgur.com/fUKXy.jpg – 2014-11-03 13:03:12