c# - 使用 RestSharp 将 JSON 反序列化为对象或数组

标签 c# json restsharp

我正在处理 Xamarin 项目。基本上,我想从 API 接收数据并显示它。为此,我正在使用 RestSharp。

这是我的 API 请求代码。

string test;
test = "yAHO0SsAmjJi1qTZGcK3sMHHIhWTN4Yq";
string s = string.Format("http://192.168.1.4:3116/api/user/getuser/{0}", test);

client = new RestClient(s);
request = new RestRequest(Method.GET);
request.AddHeader("Cache-Control", "no-cache");
request.AddHeader("Content-Type", "application/json");
IRestResponse response2 = client.Execute(request);

这是我收到的 JSON 对象。

{
    "id": 1,
    "token": "yAHO0SsAmjJi1qTZGcK3sMHHIhWTN4Yq",
    "email": "some email",
    "password": "testpassword",
    "currentCompany": "some company",
    "currentRole": "Software Developer",
    "date": "Something",
    "name": "Some name",
    "lastName": "Some surname",
    "headLine": "Some text",
    "education": "University of Hotshots",
    "country": "Who cares",
    "imageLocation": "Some url"
}

这是我使用网站为它创建的类:json2csharp.com/

class User
{
    public int Id { get; set; }
    public string Token { get; set; }
    public string Email { get; set; }
    public string Password { get; set; }
    public string CurrentCompany { get; set; }
    public string CurrentRole { get; set; }
    public string Date { get; set; }
    public string Name { get; set; }
    public string LastName { get; set; }
    public string HeadLine { get; set; }
    public string Education { get; set; }
    public string Country { get; set; }
    public string ImageLocation { get; set; }
}

我如何更改我的代码,以便我可以反序列化对上述类实例的响应,以便我可以使用它来处理数据?我阅读了此处的帖子并尝试了解决方案,但它们似乎对我不起作用。所以,我发布了这个问题。

使用数组也是一种选择;我可以使用它。作为引用,请参阅 PHP 的 $array = json_decode($somepostrequest, true),它将 JSON 对象转换为关联数组。您可以只调用对象的 $array['email']

最佳答案

使用Newtonsoft.JSON将 JSON 反序列化为对象(反之亦然)。它非常简单并且可以免费使用。还有一个 NugetPackage 可用。
安装后,您只需执行以下行即可获取所需的对象。

User userObj = Newtonsoft.Json.JsonConvert.DeserializeObject<User>(jsonString);

关于c# - 使用 RestSharp 将 JSON 反序列化为对象或数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48142142/

相关文章:

c# - 将 linq 查询结果转换为枚举

javascript - 如何从 JSON 对象中删除对象?

api - Rest API 调用,使用 RestSharp 调用 ASP.NET Web API

python - 来自通过 Scrapyd 部署的 Scrapy Spider 的自定义 JSON 响应

c# - 如何使用RestSharp处理可选的UrlSegment参数?

c# - RestSharp 在等待响应时无法转换对象

c# - 从 asp.net 导出数据到 excel 时添加自定义文本

c# - TabItem 中的新窗口?

c# - 无法让 RhinoMocks 发出遵循通用类型限制规则的模拟

java - 如何修改响应并绑定(bind)DTO