我对此非常不适应。在 C# 中,我正在编写一种使用 REST 从网站取回数据的方法。根据网站上的文档,我应该使用这样的东西:
var client = new RestClient(url + "token");
var request = new RestRequest(Method.POST);
request.AddParameter("application/x-www-form-urlencoded",
"grant_type=password&username=" + UserName +
"&password=" + Password +
"&tenant=" + Company,
ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
获得如下所示的响应:
{
"access_token": "generated_token_value",
"token_type": "bearer",
"expires_in": 2591999
}
但是,我不知道如何阅读该信息。我假设 JSON 响应在我的“响应”变量中,但除此之外我不知所措。我做了一些挖掘,发现 Json.NET 应该会有帮助,但我无法理解。他们的文档建议:
Product deserializedProduct = JsonConvert.DeserializeObject<Product>(output);
但是,如果我将其转换为适合我的内容(然后创建“响应”类):
Responses responses = JsonConvert.DeserializeObject<Responses>(response);
我在“响应”下的 VS 中收到错误消息“无法从‘RestSharp.IRestResponse’转换为‘字符串’。
我觉得我只需要一点点插入就可以克服这个困难。
最佳答案
如果您转到 RestSharp
的存储库你会看到它有一个名为 Content
的特殊属性其中包含字符串格式的 JSon。
现在您可以使用 JsonConvert.DeserializeObject<Responses>(response.Content);
检索您的对象。
关于c# - JSON 反序列化格式不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43917163/