1. 程式人生 > >C#操作json型別資料

C#操作json型別資料

將物件序列化為 JavaScript 物件表示法 (JSON),並將 JSON 資料反序列化為物件。 此類不能繼承。

//  msdn 例子:

namespace SL_DataContractJsonSerializer
{
    public partial class Page : UserControl
    {
        public Page()
        {
            InitializeComponent();
        }

        //This uses an event handler, not SL data binding
        void OnClick(object sender, EventArgs args)
        {
            txtOutput1.Text = "Create a User object and serialize it.";
            string json = WriteFromObject();
            txtOutput2.Text = json.ToString(); // Displays: {"Age":42,"Name":"Bob"}

            txtOutput3.Text = "Deserialize the data to a User object.";
            string jsonString = "{'Name':'Bill', 'Age':53}";
            User deserializedUser = ReadToObject(jsonString);
            txtOutput4.Text = deserializedUser.Name; // Displays: Bill
            txtOutput5.Text = deserializedUser.Age.ToString(); // Displays: 53
        }
        // Create a User object and serialize it to a JSON stream.
        public static string WriteFromObject()
        {
            //Create User object.
            User user = new User("Bob", 42);

            //Create a stream to serialize the object to.
            MemoryStream ms = new MemoryStream();

            // Serializer the User object to the stream.
            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(User));
            ser.WriteObject(ms, user);
            byte[] json = ms.ToArray();
            ms.Close();
            return Encoding.UTF8.GetString(json, 0, json.Length);

        }

        // Deserialize a JSON stream to a User object.
        public static User ReadToObject(string json)
        {
            User deserializedUser = new User();
            MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json));
            DataContractJsonSerializer ser = new DataContractJsonSerializer(deserializedUser.GetType());
            deserializedUser = ser.ReadObject(ms) as User;
            ms.Close();
            return deserializedUser;
        }

    }

    [DataContract]
    public class User
    {
        [DataMember]
        public string Name { get; set; }

        [DataMember]
        public int Age { get; set; }

        public User() { }

        public User(string newName, int newAge)
        {
            Name = newName;
            Age = newAge;
        }

    }

}

可以抽象成如下類:
public class JsonHelper
    {
        /// <summary>
        /// 生成Json格式
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string GetJson<T>(T obj)
        {
            DataContractJsonSerializer json = new DataContractJsonSerializer(obj.GetType());
            using (MemoryStream stream = new MemoryStream())
            {
                json.WriteObject(stream, obj);
                string szJson = Encoding.UTF8.GetString(stream.ToArray()); 
                return szJson;
            }
        }
        /// <summary>
        /// 獲取Json的Model
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="szJson"></param>
        /// <returns></returns>
        public static T ParseFromJson<T>(string szJson)
        {
            T obj = Activator.CreateInstance<T>();
            using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(szJson)))
            {
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
                return (T)serializer.ReadObject(ms);
            }
        }
    }

/// <summary>
        /// 反回JSON資料到前臺
        /// </summary>
        /// <param name="dt">資料表</param>
        /// <returns>JSON字串</returns>
        public string DataTableToJson(DataTable dt)
        {
            StringBuilder JsonString = new StringBuilder();
            if (dt != null && dt.Rows.Count > 0)
            {
                JsonString.Append("{ ");
                JsonString.Append("\"TableInfo\":[ ");
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    JsonString.Append("{ ");
                    for (int j = 0; j < dt.Columns.Count; j++)
                    {
                        if (j < dt.Columns.Count - 1)
                        {
                            JsonString.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":" + "\"" + dt.Rows[i][j].ToString() + "\",");
                        }
                        else if (j == dt.Columns.Count - 1)
                        {
                            JsonString.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":" + "\"" + dt.Rows[i][j].ToString() + "\"");
                        }
                    }
                    if (i == dt.Rows.Count - 1)
                    {
                        JsonString.Append("} ");
                    }
                    else
                    {
                        JsonString.Append("}, ");
                    }
                }
                JsonString.Append("]}");
                return JsonString.ToString();
            }
            else
            {
                return null;
            }
        }

//還有一種方式操作json型別資料:
public static class JsonTableHelper
    {
        /// <summary> 
        /// 返回物件序列化 
        /// </summary> 
        /// <param name="obj">源物件</param> 
        /// <returns>json資料</returns> 
        public static string ToJson(this object obj)
        {
            JavaScriptSerializer serialize = new JavaScriptSerializer();
            return serialize.Serialize(obj);
        }

        /// <summary> 
        /// 控制深度 
        /// </summary> 
        /// <param name="obj">源物件</param> 
        /// <param name="recursionDepth">深度</param> 
        /// <returns>json資料</returns> 
        public static string ToJson(this object obj, int recursionDepth)
        {
            JavaScriptSerializer serialize = new JavaScriptSerializer();
            serialize.RecursionLimit = recursionDepth;
            return serialize.Serialize(obj);
        }

        /// <summary> 
        /// DataTable轉為json 
        /// </summary> 
        /// <param name="dt">DataTable</param> 
        /// <returns>json資料</returns> 
        public static string ToJson(DataTable dt)
        {
            Dictionary<string, object> dic = new Dictionary<string, object>();

            int index = 0;
            foreach (DataRow dr in dt.Rows)
            {
                Dictionary<string, object> result = new Dictionary<string, object>();

                foreach (DataColumn dc in dt.Columns)
                {
                    result.Add(dc.ColumnName, dr[dc].ToString());
                }
                dic.Add(index.ToString(), result);
                index++;
            }
            return ToJson(dic);
        }
    }