使用C#调用API时,消除Json字符串中的奇怪字符?

时间:2016-02-10 12:19:42

标签: c# json tags json.net

我正在为我的公司开发一个网站,我想在那里为特定的人标记技能。因此,stackoverflow中显示的编程标记是一个有价值的来源。所以我想得到stackoverflow的标签db。

我找到了一个API。

API for the TAGS

所以我要做的是读取这个json字符串并通过页面forloop获取标签并将它们保存在数据库中。

private static void ReadJson()
    {
        HttpClient client = new HttpClient();

        //DefaultRequestHeader to Json
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        //Create an instance of HttpResponse & invoke the service asynchronously
        HttpResponseMessage response = client.GetAsync("https://api.stackexchange.com/2.2/tags?page=400&pagesize=100&order=desc&sort=popular&site=stackoverflow").Result;

        //Http Status code 200
        if (response.IsSuccessStatusCode)
        {
            //Read response content result into string variable
            string JSON = response.Content.ReadAsStringAsync().Result;
            //Deserialize the string(JSON) object
            var jObj = (JObject)JsonConvert.DeserializeObject(JSON);

            //access items from anonymous (Json object) type and add to the list
            var result = jObj["items"].Select(item => new
            {
                name = item["name"]

            }).ToList();

            //output the data || NOTE: **NSERT into database table**
            foreach (var item in result)
            {
                Console.WriteLine(item.name);
            }
        }
    }

所以在string JSON = response.Content.ReadAsStringAsync().Result;

方法它显示了一些我们的charachters(triangels和形状)因为那个过程停在那里。

0\0\0�Z�n�8\f��<�E/S��,-�cYtuI�\f�ߗf\a�g�

我在这里做错了什么?

如果有任何方法可以实现这一点,请提供您的答案。

感谢。

1 个答案:

答案 0 :(得分:1)

您获得的是压缩响应。因此,不要将其作为字符串读取,而是将其作为byte []读取,解压缩,然后您将找到您的JSON字符串。

static async void DoStuff()
{
    HttpClient client = new HttpClient();
    var bytes = await client.GetByteArrayAsync("https://api.stackexchange.com/2.2/tags?page=400&pagesize=100&order=desc&sort=popular&site=stackoverflow");
    var decompressedJson = new StreamReader(new GZipStream(new MemoryStream(bytes), CompressionMode.Decompress)).ReadToEnd();

    // decompressedJson will now contain '{"items":[{"has_synonyms":false, .....'
    // Continue with deserialization of JSON
}

static void Main(string[] args)
{
    Task t = new Task(DoStuff);
    t.Start();

    Console.WriteLine("Doing stuff");
    Console.ReadLine();
}

}

您可以从那里继续反序列化。请记住,当您发送过多请求时,API会抛出错误。