C# 对象与JSON字符串互相转换的几种方式

随着 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

        /// 
        /// Json转换成对象
        /// 
        /// 
        /// 
        /// 
        public static T JsonToObject(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;


        }


        /// 
        /// 对象转换成JSON
        /// 
        /// 
        /// 
        /// 
        public static string ObjectToJSON(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(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(json);    //将json数据转化为对象类型并赋值给list
            string result = list.result;
            string res_info = list.res_info;
            string order_num = list.queryorder_info.order_num;
            List 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;
        }


功能对比

C# 对象与JSON字符串互相转换的几种方式_第1张图片

性能对比

C# 对象与JSON字符串互相转换的几种方式_第2张图片

相关工具网站:

JSON转C#实体类

相关参考:

https://www.newtonsoft.com/json

DataContractJsonSerializer 类

c# json数据解析——将字符串json格式数据转换成对象

Json.net实现方便的Json转C#(dynamic动态类型)对象

C# JSON和对象之间互相转换

C# 对象与JSON串互相转换

你可能感兴趣的:(C# 对象与JSON字符串互相转换的几种方式)