.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)才行。

posted @   码农神说  阅读(430)  评论(0编辑  收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示