将API中的JSON数据解析和过滤到C#应用程序中。

问题描述 投票:-1回答:1

我的目标是从 "病毒追踪器 "API中检索JSON数据,并将其解析成一个标签。这是为我的IB个人项目,所以我刚开始学习c#。找到这段旧的代码,并试着修复它,它能用基本的GET API工作,但它不能用我正在使用的那个。(英语不是我的主要语言)

邮政员的答复

{
   "results": [
      {
         "total_cases": 5954607,
         "total_recovered": 2622507,
         "total_unresolved": 2255875,
         "total_deaths": 363208,
         "total_new_cases_today": 53700,
         "total_new_deaths_today": 1659,
         "total_active_cases": 45257,
         "total_serious_cases": 2698001,
         "total_affected_countries": 213,
         "source": {
            "url": "https://thevirustracker.com/"
         }
      }
   ],
   "stat": "ok"
}

C#代码

//Creating Client connection 
        RestClient restClient = new RestClient("https://thevirustracker.com/free-api?global=stats");


        //Creating request to get data from server
        RestRequest restRequest = new RestRequest("total_cases", Method.GET);


        // Executing request to server and checking server response to the it
        IRestResponse restResponse = restClient.Execute(restRequest);


        // Extracting output data from received response
        string response = restResponse.Content;

        // Parsing JSON content into element-node JObject
        var jObject = JObject.Parse(restResponse.Content);

        //Extracting Node element using Getvalue method
        string cases = jObject.GetValue("total_cases").ToString();
        label1.Text = (cases);

ERROR

An unhandled exception of type 'Newtonsoft.Json.JsonReaderException' occurred in Newtonsoft.Json.dll
Unexpected character encountered while parsing value: <. Path '', line 0, position 0.

我的这段代码的最终目标是,label1显示 "5954607"

请记住,我真的是新手,所以如果你能解释一下你对代码的修改,我真的很感激。

c# json restsharp
1个回答
0
投票

你没有正确使用RestRequest或者初始化RestClient错误。

如果你在RestClient中使用的那个url是整个url,那么你就不需要在RestRequest中使用 "资源"。

由于这个错误,你得到了一个HTML响应,并以错误的方式显示出来。

解析值时遇到意外字符:<。路径'',第0行,位置0。

的值:<。restResponse.Content 可能从 <html 而这不是有效的JSON。

Json的有效载荷比你编码的要复杂一些。结果对象持有一个数组,其中有你的stat属性的对象。

把这些修正放在一起就得到了这个代码。

RestClient restClient = new RestClient("https://thevirustracker.com/free-api?global=stats");

//Creating request to get data from server
RestRequest restRequest = new RestRequest(null, DataFormat.Json);

// Executing request to server and checking server response to the it
IRestResponse restResponse = restClient.Execute(restRequest);

// Extracting output data from received response
string response = restResponse.Content;

// Parsing JSON content into element-node JObject
var jObject = JObject.Parse(restResponse.Content);

//Extracting 
// the object has a results property 
// that is an array with one item (zero-based)
// on index 0 there is an object
// that has a property total_cases
string cases = (string) jObject["results"][0]["total_cases"];
label1.Text = (cases);
© www.soinside.com 2019 - 2024. All rights reserved.