欢迎光临
我们一直在努力

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

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

功能对比

性能对比

赞(0) 打赏
分享到: 更多 (0)

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

今日种种,似水无痕,明夕何夕,君已末路。

联系我们联系我们

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏