c# - 如何在 RestSharp 中反序列化 JSON?

标签 c# json restsharp

我刚刚开始使用 RestSharp 进行开发,但遇到了早期障碍。我想一旦我理解了这个简单但关键的概念,我就应该开始运行了。在稍后进行标准调用之前,我需要返回一个访问 token 。我已经设置了以下从 json2csharp.com 生成的类:

    public class AccessToken
{
    public string Instance_Url { get; set; }
    public string Token { get; set; }
    public string Expiration_date { get; set; }
    public string Refresh_Token { get; set; }
}

public class RootObject
{
    public AccessToken Access_Token { get; set; }
}

我在单击按钮时编写了以下代码:

        var tokenclient = new RestClient();
        tokenclient.BaseUrl = "https://url";
        tokenclient.Authenticator = new HttpBasicAuthenticator("username", "password");
        var tokenrequest = new RestRequest(Method.GET);
        tokenrequest.RequestFormat = DataFormat.Json;
        IRestResponse tokenresponse = tokenclient.Execute(tokenrequest);
        var content = tokenresponse.Content;
        RestSharp.Deserializers.JsonDeserializer deserial = new JsonDeserializer();
        var des = deserial.Deserialize<AccessToken>(tokenresponse);

我能够将以下 JSON 作为字符串返回:

{
"Access_Token": {
"Instance_Url": "https://url",
"Token": "StringToken",
"Expiration_date": "9/30/2015 6:15:27 PM",
"Refresh_Token": "StringToken"
}
}

但是,当我拉取 des.Token 时,它返回一个空值。有人可以指出我的错误吗?

最佳答案

using Newtonsoft.Json;
var response = client.DownloadString(url + queryString);
ResponseModel<string> dataResponse = new ResponseModel<string>();
if (!string.IsNullOrEmpty(response))
{
        dataResponse = JsonConvert.DeserializeObject<ResponseModel<string>>(response);
}

关于c# - 如何在 RestSharp 中反序列化 JSON?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26127606/

相关文章:

c# - 需要将javascript代码转换为c#

json - 亚马逊社交网络 : JSON toasts to Windows Phones

json - 特使配置

json - 如何在 Odoo Controller 中获取 JSON 数据?

c# - 如何从 docusign 检索已签名的用户文档?

.net-4.0 - 如何使用 RESTSharp 和 .net 4.0 将文件上传到机架空间?

c# - DataTable load() 约束错误

c# - 比较两个以逗号分隔的字符串是否匹配的最短代码是什么?

c# - 将异步方法合并到一个任务中

c# - 在 Azure 函数中使用 RestSharp 调用 HTTPS 会给出 "The SSL connection could not be established"