2012-02-02 123 views
1

如何從我的json對象中打印出一個選定的字段,而無需爲它創建類,此刻它打印出整個json對象,但我只想打印出選定的字段像Console.WriteLine(response.venues.name);從json對象中打印選擇值

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using Newtonsoft.Json; 
using Newtonsoft.Json.Linq; 

namespace FourSquareTest 
{ 
class Program 
{ 
    static void Main(string[] args) 
    { 
     using (var webClient = new System.Net.WebClient()) 
     { 
      var json = webClient.DownloadString("https://api.foursquare.com/v2/venues/search?ll=40.7,-74&query=mcdonalds&client_id=XXXXXXX&client_secret=XXXXXXXX&v=20120101"); 
      // Now parse with JSON.Net 

      JObject parsed = JObject.Parse(json); 
      foreach (var pair in parsed) 
      { 
       Console.WriteLine("{0}: {1}", pair.Key, pair.Value); 

      } 

     } 


    } 
} 
} 

回答

1

嘗試

JObject parsed = JObject.Parse(json); 
JToken response = parsed["response"]; 
JArray venues = (JArray)response["venues"]; 
JValue names = (JValue)venues[1]["name"]; 

但我沒有庫進行測試,所以這只是基於文檔。

+0

哎呀我忘了添加「使用Newtonsoft.Json.Linq.JObject;」但現在它得到一個錯誤標識符預期 – Dorf 2012-02-02 05:11:39

+0

'Newtonsoft.Json.Linq.JObject'不包含'Items'的定義,並且沒有擴展方法'Items'接受類型爲'Newtonsoft.Json.Linq.JObject'的第一個參數被發現(你是否缺少使用指令或程序集引用?) – Dorf 2012-02-02 05:18:10

+0

對不起,這是項目不是項目,修復。我只是引用http://james.newtonking.com/projects/json/help/html/T_Newtonsoft_Json_Linq_JObject.htm – Corylulu 2012-02-02 05:23:16