【问题标题】:Eliminate weird characters in Json string when calling the API by using C#?使用C#调用API时消除Json字符串中的奇怪字符?
【发布时间】:2016-02-10 12:19:42
【问题描述】:

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

我找到了一个 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=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;

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

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

我在这里做错了什么?

如果有任何方法可以做到这一点,请贡献你的答案。

谢谢。

【问题讨论】:

    标签: c# json tags json.net


    【解决方案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 会抛出错误。

    【讨论】:

    • 那是因为它是一个异步操作。我添加了一个任务框架来展示它的工作原理。请记住,如果您发送垃圾邮件,StackExchange API 会引发限制错误,因此您最好在开发应用程序时将字符串保存到记事本或其他东西。
    猜你喜欢
    • 2021-12-13
    • 1970-01-01
    • 2018-07-27
    • 2021-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多