[英]Deserialize object in Json response to array C#
目前,我正在使用Xamarin.Forms編寫移動應用程序,而我的問題是,我需要使用單獨的變量而不是一個字符串輸出來響應API的響應。
我的API輸出:
{"error":false,"user":{"id":3,"email":"root@root.de","vorname":"root","nachname":"toor","wka":"wka1"}}
我正在使用Newtonsoft反序列化響應,我認為問題出在"user":{...}
后面的大括號"user":{...}
因為我可以打印出public bool error { get; set; }
public bool error { get; set; }
public bool error { get; set; }
但其他var無效。
class JsonContent
{
public bool error { get; set; }
public int id { get; set; }
public string email { get; set; }
public string vorname { get; set; }
public string nachname { get; set; }
public string wka { get; set; }
}
測試:
JsonContent j = JsonConvert.DeserializeObject<JsonContent>(response.Content);
bool pout = j.error; //output: false
JsonContent j = JsonConvert.DeserializeObject<JsonContent>(response.Content);
int pout = j.id; //output: 0
您為JSON使用的C#類不正確。
它應該是
public class User
{
public int id { get; set; }
public string email { get; set; }
public string vorname { get; set; }
public string nachname { get; set; }
public string wka { get; set; }
}
public class JsonContent
{
public bool error { get; set; }
public User user { get; set; }
}
然后可以將JSON反序列化為C#對象
您可以使用一些json到c#轉換器來獲取模型,即https : //jsonutils.com,http://json2csharp.com 。 當您必須獲取大型json模型時,它將為您提供幫助。
public class User
{
public int id { get; set; }
public string email { get; set; }
public string vorname { get; set; }
public string nachname { get; set; }
public string wka { get; set; }
}
public class Example
{
public bool error { get; set; }
public User user { get; set; }
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.