我是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"));
我只想显示列表框1中具有"category_id":"9"的用户你能帮我如何过滤这些数据吗?我是一名学生,是c#windows手机的新手。谢谢
您通常希望使用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/en-us/library/vstudio/bb397926.aspx