1 /// <summary> 2 /// 把对象序列化 JSON 字符串 3 /// </summary> 4 /// <typeparam name="T">对象类型</typeparam> 5 /// <param name="obj">对象实体</param> 6 /// <returns>JSON字符串</returns> 7 public static string GetJson<T>(T obj) 8 { 9 //记住 添加引用 System.ServiceModel.Web 10 /** 11 * 如果不添加上面的引用,System.Runtime.Serialization.Json; Json是出不来的哦 12 * */ 13 DataContractJsonSerializer json = new DataContractJsonSerializer(typeof(T)); 14 using (MemoryStream ms = new MemoryStream()) 15 { 16 json.WriteObject(ms, obj); 17 string szJson = Encoding.UTF8.GetString(ms.ToArray()); 18 return szJson; 19 } 20 }