从 RestSharp 响应反序列化 JSON
Deserializing JSON from RestSharp response
我收到来自此 API 网页的 JSON 结果 (https://flagrantflop.com/api/endpoint.php?api_key=13b6ca7fa0e3cd29255e044b167b01d7&scope=team_stats&season=2019-2020&season_type=regular&team_name=Atlanta%20Hawks)
使用 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);
我已经测试了 URL 和指定团队的请求部分,两者都有效。
我知道有很多反序列化 JSON 的方法,但不确定最好的方法。
请求无效,因为您在 RestRequest
中提供的参数被视为基于基本 URI 的自己的页面。
您可以通过使用当前设置调用 client.BuildUri(request)
来验证这一点——您会看到已解析的 URL 是 https://flagrantflop.com/api/Atlanta Hawks, which is why you weren't getting the proper JSON response. 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");
之后,您可以让 RestSharp 自动反序列化您的响应:
RootObject response = client.Get<RootObject>(request);
默认情况下,这使用 SimpleJson 反序列化您的对象。
我收到来自此 API 网页的 JSON 结果 (https://flagrantflop.com/api/endpoint.php?api_key=13b6ca7fa0e3cd29255e044b167b01d7&scope=team_stats&season=2019-2020&season_type=regular&team_name=Atlanta%20Hawks)
使用 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);
我已经测试了 URL 和指定团队的请求部分,两者都有效。
我知道有很多反序列化 JSON 的方法,但不确定最好的方法。
请求无效,因为您在 RestRequest
中提供的参数被视为基于基本 URI 的自己的页面。
您可以通过使用当前设置调用 client.BuildUri(request)
来验证这一点——您会看到已解析的 URL 是 https://flagrantflop.com/api/Atlanta Hawks, which is why you weren't getting the proper JSON response. 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");
之后,您可以让 RestSharp 自动反序列化您的响应:
RootObject response = client.Get<RootObject>(request);
默认情况下,这使用 SimpleJson 反序列化您的对象。