2016-05-12 109 views
-2

我的C#代碼有問題。我不知道如何解決。我只想從json獲得所有標題。 它在顯示錯誤:我無法解析JSON字符串

var obj = JObject.Parse(jsons); 

「意外的字符在解析值遇到:路徑 '',線 0,位置0」。

public void getTitle() 
{ 
    ArrayList myTitle = new ArrayList(); 
    string url = "https://www.fiverr.com/gigs/endless_page_as_json?host=subcategory&type=endless_auto&category_id=3&sub_category_id=154&limit=48&filter=auto&use_single_query=true&page=1&instart_disable_injection=true"; 
    using (var webClient = new System.Net.WebClient()) 
    { 
     var jsons = webClient.DownloadString(url); 
     if (jsons != null) 
     { 
      var obj = JObject.Parse(jsons); 
      var urll = (string)obj["gigs"]["title"]; 
      myNode1.Add(urll); 
     } 
     else 
     { 
      MessageBox.Show("nothing"); 
     }    
    } 
} 
+0

Swow waht value has'var jsons'。 – BWA

+0

當您直接打開網站時,它會自動下載一個包含所需JSON的文件。你想要的是解析這個文件中的JSON,而不是網站的源代碼。 –

+0

你需要解壓縮gzip內容(這就是你從url獲得的內容),你可以使用WebRequest並將它的AutomaticDecompression屬性設置爲DecompressionMethods.GZip:http://stackoverflow.com/questions/33080674/read-httpwebreponse- using-getresponsestream-readtoend-return-strange-characters –

回答

2

WebClient類將是沒有幫助在這種情況下,返回的數據是gzip壓縮格式。令人困惑的是,當瀏覽器中瀏覽相同的URL時,它會顯示純文本,因爲解壓縮任務是由瀏覽器自動執行的。

以下代碼片段可以解決您的問題。在訪問title屬性之前,還缺少數組索引:

public void getTitle() 
{ 
    ArrayList myTitle = new ArrayList(); 
    string url = "https://www.fiverr.com/gigs/endless_page_as_json?host=subcategory&type=endless_auto&category_id=3&sub_category_id=154&limit=48&filter=auto&use_single_query=true&page=1&instart_disable_injection=true"; 

    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); 
    request.AutomaticDecompression = DecompressionMethods.GZip; 
    HttpWebResponse response = request.GetResponse() as HttpWebResponse; 
    using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(response.CharacterSet))) 
    { 
     var jsons = reader.ReadToEnd(); 
     if (jsons != null) 
     { 
      var obj = JObject.Parse(jsons); 
      var urll = (string)(obj["gigs"][0]["title"]); //returns: design a Tshirt for you   
     } 
    } 
}