简体   繁体   English

从 RestSharp 响应反序列化 JSON

[英]Deserializing JSON from RestSharp response

I am receiving a JSON result from this API web page ( https://flagrantflop.com/api/endpoint.php?api_key=13b6ca7fa0e3cd29255e044b167b01d7&scope=team_stats&season=2019-2020&season_type=regular&team_name=Atlanta%20Hawks )我从这个 API 网页收到一个 JSON 结果( https://flagrantflop.com/api/endpoint.php?api_key=13b6ca7fa0e3cd29255e044b167b01d7&scope=team_stats&season=2019-2020&season_type=regular&team_name=Atl​​anta%2

Using the RestSharp library, so far I've got this:使用 RestSharp 库,到目前为止我已经得到了这个:

var client = new RestClient("https://flagrantflop.com/api/endpoint.php?api_key=13b6ca7fa0e3cd29255e044b167b01d7&scope=team_stats&season=2019-2020&season_type=regular&team_name=");

var request = new RestRequest("Atlanta Hawks", DataFormat.Json);

var response = client.Get(request);

I have tested the URL and the request part that specifies the team and both work.我已经测试了 URL 和指定团队的请求部分,两者都有效。

I know there are a number of methods of deserializing the JSON, however not sure the best way.我知道有多种反序列化 JSON 的方法,但不确定最好的方法。

The request isn't working because the argument you're supplying in RestRequest is treated as its own page stemming off the base URI.该请求不起作用,因为您在RestRequest提供的参数被视为它自己的页面,该页面源于基本 URI。

You can verify that by calling client.BuildUri(request) with your current setup―you'll see that the resolved URL is https://flagrantflop.com/api/Atlanta Hawks , which is why you weren't getting the proper JSON response.您可以通过使用当前设置调用client.BuildUri(request)来验证这一点——您会看到解析的 URL 是https://flagrantflop.com/api/Atlanta Hawks ,这就是为什么您没有获得正确的 JSON回复。 I recommend rewriting the request like this, but there are other valid ways :我建议像这样重写请求,但还有其他有效的方法

var client = new RestClient("https://flagrantflop.com/api/")
    .AddDefaultQueryParameter("api_key", "13b6ca7fa0e3cd29255e044b167b01d7")
    .AddDefaultQueryParameter("scope", "team_stats")
    .AddDefaultQueryParameter("season", "2019-2020")
    .AddDefaultQueryParameter("season_type", "regular");

var request = new RestRequest("endpoint.php")
    .AddQueryParameter("team_name", "Atlanta Hawks");

After that, you can have RestSharp automatically deserialize your response:之后,您可以让 RestSharp 自动反序列化您的响应:

RootObject response = client.Get<RootObject>(request);

By default, this uses SimpleJson to deserialize your object.默认情况下,它使用 SimpleJson 来反序列化您的对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM