[英]How to query data from json in c# windows phone
我是Windows Phone開發人員的新手。 我正在開發一個從Web服務獲取json並將其解析並顯示給應用程序的應用程序。 我用json.net解析它。 這是我的json文件:
[
{
"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"
}
]
所以我在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; }
}
這是我在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"));
我只想顯示listbox1上具有“ category_id”:“ 9”的用戶,您可以幫助我如何過濾此數據嗎? 我是學生,並且是C#Windows Phone的新功能。 謝謝!
通常,您通常希望使用LINQ來操作List<RootObject>
,例如:
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);
如果API本身沒有終結點,僅允許您查詢那些帶有category_id : 9
記錄,那么您將必須在客戶端進行過濾以填充列表框。 一種常用的簡單方法是使用LINQ 。
這是LINQ語法的示例:
var categoryNineOnly = data.Where(x=>x.category_id == 9)
這里有更多詳細信息:
http://msdn.microsoft.com/zh-CN/library/vstudio/bb397926.aspx
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.