简体   繁体   中英

How to query data from json in c# windows phone

I am new to windows phone dev. I'm working on an app that fetch json from a web service and parse it and display it to the app. I used json.net to parse it. here's my json file:

[
{
    "id": "001",
    "title": "title1",
    "content": "sample content",
    "category_id": "3",
    "image": "defaultimg.jpg"
},

{
    "id": "021",
    "title": "title2",
    "content": "sample content",
    "category_id": "1",
    "image": "defaultimg2.jpg"
},

{
    "id": "011",
    "title": "title3",
    "content": "sample content",
    "category_id": "3",
    "image": "defaultimg22.jpg"
},

{
    "id": "008",
    "title": "title24",
    "content": "sample content",
    "category_id": "2",
    "image": "defaultimg12.jpg"
},
{
    "id": "121",
    "title": "title12",
    "content": "sample content",
    "category_id": "3",
    "image": "defaultimg27.jpg"
}
]

so I came up with this class with the help of json2csharp.com

    public class RootObject
{
    public string id { get; set; }
    public string title { get; set; }
    public string content { get; set; }
    public string category_id { get; set; }
    public string image { get; set; }
}

here's my code in cs

 var data = new WebClient();
            Observable
              .FromEvent<DownloadStringCompletedEventArgs>(data, "DownloadStringCompleted")
              .Subscribe(r =>
              {
                  var deserialized =
                    JsonConvert.DeserializeObject<List<RootObject>>(r.EventArgs.Result);
                  ListBox1.ItemsSource = deserialized;
              });
            data.DownloadStringAsync(
              new Uri("http://sampleurl.com/xyz/myjson.aspx"));

I want to display only those who has "category_id": "9" on the listbox1 can you help me how to filter this data? im a student and new in c# windows phone. Thanks!

You would generally want to use LINQ to manipulate your List<RootObject> , something like:

var deserialized = JsonConvert.DeserializeObject<List<RootObject>>(r.EventArgs.Result);

// select only RootObjects with category_id equal to 9
ListBox1.ItemsSource = deserialized.Where(r => r.category_id == 9);

If the API itself does not have an endpoint that allows you to query for only those records with category_id : 9 then you'll have to do the filtering at the client to populate your listbox. One common and easy way to do that is with LINQ .

Here is an example of what the LINQ syntax would look like:

  var categoryNineOnly = data.Where(x=>x.category_id == 9)

Much more detail here:

http://msdn.microsoft.com/en-us/library/vstudio/bb397926.aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM