用数组反序列化JSon结果

时间:2014-11-07 19:54:55

标签: json windows-phone-8

我从json读取时遇到了一些问题。这是我得到的json:

{
"LoginName": null,
"EmailAddress": null,
"FirstName": null,
"LastName": null,
"ErrorList": [
{
"ErrorNumber": 5001,
"ErrorMessage": "Validation Error: The UserName field is required.",
"Details": null
},
{
"ErrorNumber": 5001,
"ErrorMessage": "Validation Error: The Password field is required.",
"Details": null
},
{
"ErrorNumber": 1,
"ErrorMessage": "The username or password is not correct!",
"Details": null
}
]
}

以下是我的课程:

[DataContract]
    public class User
    {
        [DataMember(Name = "LoginName")]
        public string loginName { get; set; }

        [DataMember(Name = "EmailAddress")]
        public string emailAddress { get; set; }

        [DataMember(Name = "LastName")]
        public string lastName { get; set; }

        [DataMember(Name = "FirstName")]
        public string firstName { get; set; }

        [DataMember(Name = "ErrorList")]
        public ErrorList[] errorList { get; set; }
    }
[DataContract]
    public class ErrorList
    {
        [DataMember(Name = "ErrorNumber")]
        public int errorNumber { get; set; }

        [DataMember(Name = "ErrorMessage")]
        public string errorMessage { get; set; }
    }

我可以获得LoginName和EmailAddress,但我无法获取ErrorList的元素。 以下是反序列化json结果的代码:

var res = await result.Content.ReadAsStringAsync();
var answer = JsonConvert.DeserializeObject<User>(res);
Email.Text = answer.emailAddress;

它有效,但我没有到达阵列。 有人有任何想法解决这个问题吗?

2 个答案:

答案 0 :(得分:1)

您应该使用JsonProperty更改DataMember属性。这应该有效:

public class User
{
    [JsonProperty("LoginName")]
    public string loginName { get; set; }

    [JsonProperty("EmailAddress")]
    public string emailAddress { get; set; }

    [JsonProperty("LastName")]
    public string lastName { get; set; }

    [JsonProperty("FirstName")]
    public string firstName { get; set; }

    [JsonProperty("ErrorList")]
    public ErrorList[] errorList { get; set; }
}

public class ErrorList
{
    [JsonProperty("ErrorNumber")]
    public int errorNumber { get; set; }

    [JsonProperty("ErrorMessage")]
    public string errorMessage { get; set; }
}

答案 1 :(得分:1)

正如@AbdurrahmanKöken所说,也许你应该使用JSON.NET属性而不是System.Runtime.Serialization

但是,这段代码没有任何问题。错误在其他地方。按原样使用User类,使用提供的JSON,并将其反序列化为var answer = JsonConvert.DeserializeObject<User>(yourJsonHere);,可以得到以下结果:

enter image description here

因此,反序列化后

answer.errorList.ToList().ForEach(error => 
    Console.WriteLine(@"{0}={1}", error.errorNumber, error.errorMessage));

输出

5001=Validation Error: The UserName field is required. 
5001=Validation Error: The Password field is required. 
1=The username or password is not correct!