1. 程式人生 > >C 物件與JSON字串互相轉換的幾種方式

C 物件與JSON字串互相轉換的幾種方式

分享一下我老師大神的人工智慧教程!零基礎,通俗易懂!http://blog.csdn.net/jiangjunshow

也歡迎大家轉載本篇文章。分享知識,造福人民,實現我們中華民族偉大復興!

               

隨著 Rest 風格 API 的應用越來越廣泛,物件與JSON字串互相轉換的功能也用的越來越多。這裡介紹三種方法,期中兩種為DotNet Framework .NET 3.5 及後續版本自帶的 

DataContractJsonSerializer、 JavaScriptSerializer,另一種為 Newtonsoft.Json.dll ,我選擇它的原因是因為它支援 DotNet Framework .NET 2.0。


方法一、DoNet2.0 需要藉助於Newtonsoft.Json.dll

我使用的版本是:Version 10.0.3

        // 從一個物件資訊生成Json串        public
static string ObjectToJson(object obj)       
{            return JsonConvert.SerializeObject(obj);        }        // 從一個Json串生成物件資訊        public
static object JsonToObject(string jsonString, object obj)       
{            return JsonConvert.DeserializeObject(jsonString, obj.GetType());        }


方法二、DataContractJsonSerializer

        /// <summary>        /// Json轉換成物件        /// </summary>        /// <typeparam name="T"></typeparam>        /// <param name="jsonText"></param>        /// <returns></returns>        public static T JsonToObject<T>(string jsonText)        {            // Framework 2.0 不支援            DataContractJsonSerializer s = new DataContractJsonSerializer(typeof(T));            MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonText));            T obj = (T)s.ReadObject(ms);            ms.Dispose();            return obj;        }        /// <summary>        /// 物件轉換成JSON        /// </summary>        /// <typeparam name="T"></typeparam>        /// <param name="obj"></param>        /// <returns></returns>        public static string ObjectToJSON<T>(T obj)        {            // Framework 2.0 不支援            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));            string result = string.Empty;            using (MemoryStream ms = new MemoryStream())            {                serializer.WriteObject(ms, obj);                ms.Position = 0;                using (StreamReader read = new StreamReader(ms))                {                    result = read.ReadToEnd();                }            }            return result;        }

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;        }    }}


方法三、JavaScriptSerializer

public static void JsonMy(string json)        {                                 JavaScriptSerializer js = new JavaScriptSerializer();   //例項化一個能夠序列化資料的類            ToJsonMy list = js.Deserialize<ToJsonMy>(json);    //將json資料轉化為物件型別並賦值給list            string result = list.result;            string res_info = list.res_info;            string queryorder_info = list.res_info;        }        public static void JsonMy4(string json)        {            JavaScriptSerializer js = new JavaScriptSerializer();   //例項化一個能夠序列化資料的類            ToJsonMy3 list = js.Deserialize<ToJsonMy3>(json);    //將json資料轉化為物件型別並賦值給list            string result = list.result;            string res_info = list.res_info;            string order_num = list.queryorder_info.order_num;            List<orderdetail> orderdetail = list.queryorder_info.orderdetail;            string CFTUin = orderdetail[0].CFTUin;            string HotelName = orderdetail[0].HotelName;            string ListID = orderdetail[1].ListID;            string State = orderdetail[2].State;        }


功能對比


效能對比


相關工具網站:

JSON轉C#實體類

相關參考:

https://www.newtonsoft.com/json

DataContractJsonSerializer 類

c# json資料解析——將字串json格式資料轉換成物件

Json.net實現方便的Json轉C#(dynamic動態型別)物件

C# JSON和物件之間互相轉換

C# 物件與JSON串互相轉換

           

給我老師的人工智慧教程打call!http://blog.csdn.net/jiangjunshow

這裡寫圖片描述