C#/WP7 : Working with a JSON object that includes an array of JSON objects

标签 c# json windows-phone-7 json.net

我是 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 属性并读取它,但我不能访问 data 属性中的所有内容。在我看来,这是一个 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);
}

关于C#/WP7 : Working with a JSON object that includes an array of JSON objects,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10369119/

相关文章:

windows-phone-7 - 增加小图像的可触摸目标区域?

c# - 在 WP7.5 上使用 HTML 敏捷包

c# - ASP.NET Core Web App DI 错误 - 无法构造某些服务(验证服务描述符时出错

javascript - 这种 JSON 结构是否适用于使用 d3.js 的堆叠条形图?

c# - 在 C# 中使用 IDisposable 的模板方法模式

java - 使用 jackson 创建简单的 JSON 结构

Go Lang 中的 JSON 结构到 csv

windows-phone-7 - WP7噪音检测-录制音频

c# - 将字符指针从 C# 传递到 C++

c# - 如何在新的 .NET Framework 4.6 中启用 SIMD?