如何从JArray中获取子对象到ObservableCollection中



我正在为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 Indaiatuba SP

如果我正确理解你的问题,你正试图从JSON中获得所有的"字段"对象到你的ObservableCollection<Fields>。你可以这样做:

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

相关内容

  • 没有找到相关文章

最新更新