1,泛型对象转化为Json对象
1 /// <summary> 2 /// 将对象转化为Json字符串 3 /// </summary> 4 /// <typeparam name="T">对象类型</typeparam> 5 /// <param name="instanse">对象本身</param> 6 /// <returns>JSON字符串</returns> 7 public static string ToJsonString<T>(this T instanse) 8 { 9 try 10 { 11 DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(T)); 12 using (MemoryStream ms = new MemoryStream()) 13 { 14 js.WriteObject(ms, instanse); 15 ms.Flush(); 16 ms.Seek(0, SeekOrigin.Begin); 17 StreamReader sr = new StreamReader(ms); 18 return sr.ReadToEnd(); 19 } 20 } 21 catch 22 { 23 return String.Empty; 24 } 25 }
时间: 2024-10-07 18:29:33