.NET自定义获得JSON的方法(System.Runtime.Serialization.Json)
方法如下:
public static string GetJson(object o, Type type) { DataContractJsonSerializer jsoner = new DataContractJsonSerializer(type); var ms = new MemoryStream(); jsoner.WriteObject(ms, o); byte[] jsonBytes = new byte[ms.Length]; ms.Position = 0; ms.Read(jsonBytes, 0, (int)ms.Length); return Encoding.UTF8.GetString(jsonBytes); }
在引用System.Runtime.Serialization.Json命名空间时,不但要引用System.Runtime.Serialization(3.0),还要引用System.ServiceModel.Web(3.5)才行。
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。