[英]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.