[英]Deserialize JSON to an object or an array using 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);
嘗試使用client.Execute()
的泛型重載。 RestSharp將使用其內部序列化器反序列化JSON:
var response2 = client.Execute<User>(request);
User user = response2.Data;
在RestSharp的GitHub網站上的“ 推薦用法”維基頁面上顯示了一個示例。
誠然,RestSharp的內部序列化器沒有Json.Net的全功能,但看起來您不需要花哨的東西。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.