c# - 如何从 JArray 获取子对象到 ObservableCollection

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

我正在为 Windows Phone 开发一个应用程序,其中的 ListBox 显示来自 JSON 文件的数据。我使用的是 JArray,我可以根据数组位置显示数据。但是,如果我想显示我的 JSON 文件中的所有数据(该文件没有静态数据,以后可能会修改数据)怎么办?

我的 JSON:

[
    {
        "xId": "52",
        "result": {
            "type": "Basico.Bean.MunicipioClass.TMunicipio",
            "id": 1,
            "fields": {
                "FRefCount": 0,
                "FId": 52,
                "FNome": "Sumare",
                "FEstado": "SP",
                "FPais": "Brasil"
            }
        }
    },
    {
        "xId": "52",
        "result": {
            "type": "Basico.Bean.MunicipioClass.TMunicipio",
            "id": 1,
            "fields": {
                "FRefCount": 0,
                "FId": 52,
                "FNome": "Indaiatuba",
                "FEstado": "SP",
                "FPais": "Brasil"
            }
        }
    }
]

我的代码:

InitializeComponent();

String text;


using (var store = IsolatedStorageFile.GetUserStoreForApplication())
using (var readStream = new IsolatedStorageFileStream("json.html", FileMode.Open, FileAccess.Read, FileShare.Read, store))
using (var reader = new StreamReader(readStream))
{
    text = reader.ReadToEnd();
}
{
    try
    {


        DataContext = this;

        // Your JSON string
        string json = text;

        // Parse as JObject
        JArray jObj = JArray.Parse(json);


        // Extract what you need, the "fields" property
        JToken jToken = jObj[0]["result"]["fields"];

        // Convert as Fields class instance
        Fields fields = jToken.ToObject<Fields>();

        Items = new ObservableCollection<Fields>() { fields };
    }

    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

public ObservableCollection<Fields> Items { get; set; }

public class Fields
{
    [JsonProperty(PropertyName = "FId")]
    public int FId { get; set; }

    public string FNome { get; set; }
    public string FEstado { get; set; }
    public string FPais { get; set; }
}

当我使用“[0]”时,返回的是 Sumare SP:

JToken jToken = jObj[0]["result"]["fields"];

当我使用“[1]”时,返回的是 Indaiatuba SP:

JToken jToken = jObj[1]["result"]["fields"];

我需要这样的:

Sumare SP 因达亚图巴 SP

最佳答案

如果我正确理解你的问题,你正试图从 JSON 中获取所有“字段”对象到你的 ObservableCollection<Fields> 中。 .以下是您可以如何做到这一点:

JArray jObj = JArray.Parse(json);

Items = new ObservableCollection<Fields>(
        jObj.Children().Select(jo => jo["result"]["fields"].ToObject<Fields>()));

关于c# - 如何从 JArray 获取子对象到 ObservableCollection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25266694/

相关文章:

c# - 如何使用 mongo c# 驱动程序更新数组/列表中的项目?

javascript - ajax请求浏览器限制

javascript - 在 d3 中加载多行数据的默认格式是什么?

javascript - 如何从 JavaScript 上转换的 XML 访问 JSON.@attribute

c# - Windows Phone 8 上的二维码扫描

c# - 从 C++ Windows Phone 8 应用程序引用 Facebook SDK C# WP8 的问题

c# - 独立存储不支持给定路径的格式

c# - MsChart:如何将日历周数显示为 X 轴上的标签?

c# - dotnet build 命令忽略 .editorconfig

c# - 创建表查询