我无法将JSON解析为字符串

时间:2016-05-12 09:14:57

标签: c# json string parsing url

我的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");
        }             
    }
}

1 个答案:

答案 0 :(得分: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        
        }
    }
}