Object to Json 如何支援匿名型別

rusli
Site Admin
文章: 212
註冊時間: 週三 7月 07, 2010 9:49 pm

Object to Json 如何支援匿名型別

文章rusli » 週四 7月 07, 2011 3:33 pm

參考組件:System.Web.Extensions (在 System.Web.Extensions.dll 中)

代碼: 選擇全部

  using System.Web.Script.Serialization;



代碼: 選擇全部

    public class Util
    {
        public static string ObjectToJson<T>(T[] t)
        {
            string result;

            //// 支援匿名型別
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            result = serializer.Serialize(t);

            ////Create a stream to serialize the object to.
            //using (var ms = new MemoryStream())
            //{
            //    ////// Serializer the User object to the stream.
            //    //var ser = new DataContractJsonSerializer(typeof(T[]));
            //    //ser.WriteObject(ms, t);
            //    //result = Encoding.UTF8.GetString(ms.ToArray());
            //    //ms.Close();
            //}
            return result;
        }
   }



代碼: 選擇全部

          // object[] 物件陣列 轉換 Json
            string a = Util.ObjectToJson<object>(new[] { new { a1 = "A值", a2 = "a2值", a3 = new[] { "陣列值1", "陣列值2" } } });




輸出結果:

代碼: 選擇全部

[
    {
        "a1": "A值",
        "a2": "a2值",
        "a3": [
            "陣列值1",
            "陣列值2"
        ]
    }
]

回到「C#」

誰在線上

正在瀏覽這個版面的使用者:沒有註冊會員 和 1 位訪客