0

我是 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 的学生和新手。谢谢!

4

2 回答 2

1

您通常希望使用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);
于 2013-07-11T14:33:34.783 回答
0

如果 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

于 2013-07-11T14:34:31.443 回答