DataContractJsonSerializer 类 操作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);
        }
    }

转自:https://www.cnblogs.com/chenqingwei/archive/2010/06/09/1754522.html

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
<stringobject> dic = new Dictionary<stringobject>();

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

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

posted @ 2021-08-24 08:40  sevene  阅读(262)  评论(0编辑  收藏  举报