当前位置: 代码迷 >> ASP.NET >> 关于数据转换为jason有关问题
  详细解决方案

关于数据转换为jason有关问题

热度:1182   发布时间:2013-02-25 00:00:00.0
关于数据转换为jason问题
现在数据库有一张表:
modelID ModelCName ParentID URL Icos
 10 A ss
 11 B 10 …… aa
 12 C 10 …… cc
 13 D …… dd
 14 E 13 …… ee
一张树表。
现在用asp.net 转换成jason
  [{
  modelID : "10",
  Icos: "ss",
  ModelCName : "A",
  URL:""  
  menus: [{
  modelID : "11",
  ModelCName : "B",
  Icos: "aa",
  URL : "#"
  }, {
  modelID : "12",
  ModelCName : "C",
  Icos: "cc",
  URL : "#"
  }]
  }, {
  modelID : "13",
  Icos: "dd",
  ModelCName: "D",
  URL : "#"
  menus: [{
  modelID : "14",
  ModelCName: "E",
  Icos: "ee",
  URL : "#"
  }]
请教大侠们这个方法该怎么写

------解决方案--------------------------------------------------------
System.Web.Script.Serialization.JavaScriptSerializer
------解决方案--------------------------------------------------------
先建一个对应类,然后序列化
C# code
        /// <summary>        /// Serialize object to string of json format        /// </summary>        private string JsonSerializer<T>(T t)        {            var ser = new DataContractJsonSerializer(typeof(T));            var ms = new MemoryStream();            ser.WriteObject(ms, t);            string jsonString = Encoding.UTF8.GetString(ms.ToArray());            ms.Close();            return jsonString;        }        /// <summary>        /// Deserialize string of json format to object        /// </summary>        private T JsonDeserialize<T>(string jsonString)        {            var ser = new DataContractJsonSerializer(typeof(T));            var ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));            var obj = (T)ser.ReadObject(ms);            return obj;        }
------解决方案--------------------------------------------------------
public static string ToJson(object obj)
{
System.Web.Script.Serialization.JavaScriptSerializer javaSer = new System.Web.Script.Serialization.JavaScriptSerializer();
return javaSer.Serialize(obj);
}
------解决方案--------------------------------------------------------
把数据保存在ilist中.遍历ilist.
stringbuilder str=new stringbuilder("[{");
str.append("")//你的操作.
...
...
...
str.append("}]");
接着str.ToString();

------解决方案--------------------------------------------------------
System.Web.Script.Serialization.JavaScriptSerializer


直接把你的实体类转化为json