C# json 数据循环

{
"note":"杨杨 asdfafafds",
"image":{
"url":null,
"border":null,
"height":null,
"width":null
},
"title":"根目录",
"children":[
{
"note":"asffafdsd<br>",
"image":{
"url":null,
"border":null,
"height":null,
"width":null
},
"title":"12212121",
"children":[
],
"putright":"0",
"fold":"0",
"id":"21"
},
{
"note":"第二季备注<br><br>",
"image":{
"url":"http://www.mindpin.com/images/logo/default_user.png",
"border":"1",
"height":"48",
"width":"48"
},
"title":"第二集标题",
"children":[
],
"putright":"0",
"fold":"0",
"id":"33"
}
],
"maxid":"34",
"id":"0"
}

我希望通过ID 比如 ID=33 取出
{
"note":"第二季备注<br><br>",
"image":{
"url":"http://www.mindpin.com/images/logo/default_user.png",
"border":"1",
"height":"48",
"width":"48"
},
"title":"第二集标题",
"children":[
],
"putright":"0",
"fold":"0",
"id":"33"
}

这段数据,哪位兄弟帮忙。

(请楼主耐心看完,因为是专门为你的问题写的)

1.首先需要写三个类,这个类和json中对象的数据结构应该是对应的,这里的例子可能忽略了部分属性和数据类型,仅供参考:

//Json数据的对象结构
public class MyJson
{
public List<MyTreeNodeBean> beanList { get; set; }
}

//树形结构中的对象结构
public class MyBean
{
public string id { get; set; }
public string title { get; set; }
public string note { get; set; }
public MyImage image { get; set; }
public string maxid { get; set; }
public string fold { get; set; }
public string putright { get; set; }
public List<MyTreeNodeBean> children { get; set; }

public MyBean()
{
}
}

//对象里面Image的结构
public class MyImage
{
public string url { get; set; }
public string border { get; set; }
public string height { get; set; }
public string width { get; set; }
}

2.因为json是树形结构的数据,所以需要递归遍历去寻找对应ID的对象

//这个类负责按照ID寻找对象
public class MyHelper
{
//FindById函数的重载函数,用来第一次调用
public static MyBean FindById(string id, string jsonString)
{
return FindById(id, jsonString, null);
}
//FindById递归寻找函数
public static MyBean FindById(string id, string jsonString, List<MyBean> beanList)
{
if (beanList == null) {
//第一次调用的时候,寻找的列表是最高层的根底下的对象列表
//将json数据转换成C#对应类型(用了Newtonsoft.Json)
MyJson json = JavaScriptConvert.DeserializeObject<MyJson>(jsonString);
beanList = json.beanList;
}

//遍历对象列表,寻找对应ID的对象
MyBean returnBean = null;
foreach (MyBean bean in beanList) {
if (bean.id == id) {
//找到了
returnBean = bean;
} else {
//递归寻找:
//如果不是,就寻找此对象的children列表
returnBean = FindById(id, jsonString, bean.children);
}

//如果找到,就跳出寻找
if (returnBean != null) {
break;
}
}
return returnBean;
}
}

3.使用实例:

//假设json的字符串在变量jsonString中
MyBean bean = MyHelper.FindById("33", jsonString);
if (bean != null) {
//使用查找出来的bean
}

写在最后:
以上代码仅供参考,没有经过编译测试、有可能存在书写错误。但是逻辑清晰、没有任何冗余内容。请楼主阅读以后自己在理解的基础上进行修改、改进再使用。
另外楼主如果想给分就请直接给,请不要马马虎虎把大家的回答投票,比较反感,最后祝你早日搞定这个问题~~~
温馨提示:答案为网友推荐,仅供参考
第1个回答  2009-06-22
System.Web.Script.Serialization.JavaScriptSerializer json = new JavaScriptSerializer();
json.Deserialize<T>("json字符串");//将json字符串转成指定的类。
第2个回答  2009-06-21
遍历一遍不就行了
第3个回答  2009-06-21
对不起,我帮不了你,不过我还是比较诚恳滴

如果没人帮你解决,请不要关闭,分送我吧,谢谢了!