对象与JSON字符串互相转换的功能也用的越来越多

时间:2022-03-17 06:22:39

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

[csharp]  

 

// 从一个东西信息生成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

[csharp]  

 

/// <summary> /// Json转换成东西 /// </summary> /// <typeparam></typeparam> /// <param></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></typeparam> /// <param></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; }

  

[csharp]  

 

要领三、JavaScriptSerializer

[csharp]  

 

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