.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 @ 2012-11-06 15:45  码农神说  阅读(426)  评论(0编辑  收藏  举报