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

Eliminate weird characters in Json string when calling the API by using C#?

我正在为我的公司开发一个网站,我想在其中为特定的人标记技能。因此,Whosebug 中显示的编程标签是一个有价值的来源。所以我想获取 Whosebug 的标签数据库。

我为此找到了 API。

API for the TAGS

所以我想做的是读取这个 json 字符串并在页面中进行循环以获取标签并将它们保存在数据库中。

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=Whosebug").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;

方法它显示了一些奇怪的字符(三角形和形状),因为该过程在那里停止。

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

我做错了什么?

如果有什么方法可以做到这一点,请提供您的答案。

谢谢。

您得到的是压缩响应。因此,与其将其作为字符串读取,不如将其作为字节 [] 读取,将其解压缩,您将找到 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=Whosebug");
    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 会抛出错误。