[英]I can not Parse JSON to string
我的 C# 代碼有問題。 我不知道如何修復。 我只想從 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");
}
}
}
在這種情況下, 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
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.