[英]How to query data from json in c# windows phone
I am new to windows phone dev. 我是Windows Phone开发人员的新手。 I'm working on an app that fetch json from a web service and parse it and display it to the app.
我正在开发一个从Web服务获取json并将其解析并显示给应用程序的应用程序。 I used json.net to parse it.
我用json.net解析它。 here's my json file:
这是我的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"
}
]
so I came up with this class with the help of json2csharp.com 所以我在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 这是我在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? 我只想显示listbox1上具有“ category_id”:“ 9”的用户,您可以帮助我如何过滤此数据吗? im a student and new in c# windows phone.
我是学生,并且是C#Windows Phone的新功能。 Thanks!
谢谢!
You would generally want to use LINQ to manipulate your List<RootObject>
, something like: 通常,您通常希望使用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);
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. 如果API本身没有终结点,仅允许您查询那些带有
category_id : 9
记录,那么您将必须在客户端进行过滤以填充列表框。 One common and easy way to do that is with LINQ . 一种常用的简单方法是使用LINQ 。
Here is an example of what the LINQ syntax would look like: 这是LINQ语法的示例:
var categoryNineOnly = data.Where(x=>x.category_id == 9)
Much more detail here: 这里有更多详细信息:
http://msdn.microsoft.com/en-us/library/vstudio/bb397926.aspx http://msdn.microsoft.com/zh-CN/library/vstudio/bb397926.aspx
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.