[英]Deserialize object in Json response to array C#
Currently I'm writing a mobile app with Xamarin.Forms and my problem is, that I need the response from my API in separate variables instead of one string output. 目前,我正在使用Xamarin.Forms编写移动应用程序,而我的问题是,我需要使用单独的变量而不是一个字符串输出来响应API的响应。
My API output: 我的API输出:
{"error":false,"user":{"id":3,"email":"root@root.de","vorname":"root","nachname":"toor","wka":"wka1"}}
I'm using Newtonsoft to deserialize the response and I think that the problem is the curly bracket behind "user":{...}
because I can print out public bool error { get; set; }
我正在使用Newtonsoft反序列化响应,我认为问题出在
"user":{...}
后面的大括号"user":{...}
因为我可以打印出public bool error { get; set; }
public bool error { get; set; }
public bool error { get; set; }
but the other vars are not working. 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; }
}
Tests: 测试:
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
The C# class that you have for your JSON is not correct. 您为JSON使用的C#类不正确。
It should be 它应该是
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; }
}
and then you can deserialize your JSON to your C# objects 然后可以将JSON反序列化为C#对象
You can use some json to c# converter to get the model, ie https://jsonutils.com , http://json2csharp.com . 您可以使用一些json到c#转换器来获取模型,即https : //jsonutils.com,http://json2csharp.com 。 It will help you when you have to get the model of a big json.
当您必须获取大型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.