C#/WP7:使用包含 JSON 对象数组的 JSON 对象



我是使用JSON和 JSON.net 的新手,我在使用JSON对象中的JSON对象数组时遇到问题。我正在使用 JSON.net 因为我看到的其他示例使它看起来很简单。

我正在从互联网下载以下 JSON 字符串:

{"count":2,"data":[{"modifydate":12345,"key":"abcdef", "content":"test file 1"},{"modifydate":67891,"key":"ghjikl", "content":"test file 2"}]}

我知道它需要反序列化,为此,我需要我编写的 JSON 类:

    public class NOTE
    {
        [JsonProperty(PropertyName = "count")]
        public int count { get; set; }
        [JsonProperty(PropertyName = "key")]
        public string key { get; set; }
        [JsonProperty(PropertyName = "modifydate")]
        public float modifydate { get; set; }
        [JsonProperty(PropertyName = "content")]
        public string modifydate { get; set; }
    }

所以我使用以下方法反序列化它:

NOTE note = JsonConvert.DeserializeObject<NOTE>(e.Result);

这工作正常,因为我可以访问 count 属性并读取它,但数据属性中的所有内容我都不能。在我看来,这是一个 JSON 对象数组,我遇到了麻烦,我希望能够获得所有"键"值或所有"内容"字符串的列表。

从这里尝试了很多方法,但似乎没有任何效果/我无法找到与我完全相同的情况来进行比较。

如果有人能帮我一把,那将是非常棒的:)

JSON 具有嵌套对象,而您尝试反序列化的对象没有嵌套对象。您需要适当的层次结构才能正常工作:

public class Note
{
    [JsonProperty(PropertyName = "count")]
    public int Count { get; set; }
    [JsonProperty(PropertyName = "data")]
    public Data[] Data { get; set; }
}
public class Data
{
    [JsonProperty(PropertyName = "modifydate")]
    public float ModifyDate { get; set; }
    [JsonProperty(PropertyName = "key")]
    public string Key { get; set; }
    [JsonProperty(PropertyName = "content")]
    public string Content { get; set; }
}

现在你应该能够正确地反序列化事情:

var note = JsonConvert.DeserializeObject<Note>(e.Result);
// loop through the Data elements and show content
foreach(var data in note.Data)
{
    Console.WriteLine(data.content);
}

最新更新