Search code examples
c#jsonwindows-phone-8json.net

How to get child objects from a JArray into an ObservableCollection


I am developing an app for Windows Phone, where a ListBox shows data from a JSON file. I'm using a JArray and I can display data according to an array position. But what if I want to display all data from my JSON file (the file doesn't have static data, and the data may be modified later)?

My 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"
            }
        }
    }
]

My Code:

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; }
}

When i used "[0]" the return is Sumare SP :

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

When i used "[1]" the return is Indaiatuba SP :

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

I need it like this:

Sumare SP Indaiatuba SP


Solution

  • If I understand your question correctly, you are trying to get all of the "fields" objects from the JSON into your ObservableCollection<Fields>. Here is how you can do that:

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