在Json响应数组C#中反序列化对象

时间:2017-11-03 16:38:43

标签: c# xamarin serialization json.net

目前我正在编写一个带有Xamarin.Forms的移动应用程序,我的问题是,我需要来自我的API的响应,而不是一个字符串输出。

我的API输出:

{"error":false,"user":{"id":3,"email":"root@root.de","vorname":"root","nachname":"toor","wka":"wka1"}}

我正在使用Newtonsoft反序列化响应,我认为问题是"user":{...}背后的大括号,因为我可以打印public bool error { get; set; },但其他变量不起作用。

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

2 个答案:

答案 0 :(得分:3)

您的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#对象

答案 1 :(得分:0)

您可以使用一些json到c#转换器来获取模型,即https://jsonutils.comhttp://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; }
}