日期:2014-05-16  浏览次数:20392 次

ASP.NET,string转json
本帖最后由 mcluzhi 于 2014-03-18 12:51:38 编辑

 {
     "button":[
     {
          "type":"click",
          "name":"今日歌曲",
          "key":"V1001_TODAY_MUSIC"
      },
      {
           "type":"click",
           "name":"歌手简介",
           "key":"V1001_TODAY_SINGER"
      },
      {
           "name":"菜单",
           "sub_button":[
           {
               "type":"view",
               "name":"搜索",
               "url":"http://www.soso.com/"
            },
            {
               "type":"view",
               "name":"视频",
               "url":"http://v.qq.com/"
            },
            {
               "type":"click",
               "name":"赞一下我们",
               "key":"V1001_GOOD"
            }]
       }]
 }



像上图这种json,如果通过List<T>实现
------解决方案--------------------
List<T>转Json

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public static string Obj2Json<T>(T data)
{
    try
    {
        System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(data.GetType());
        using (MemoryStream ms = new MemoryStream())
        {
            serializer.WriteObject(ms, data);
            return Encoding.UTF8.GetString(ms.ToArray());
        }
    }
&nbs