方法如下:
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)才行。