JsonHelper


/// 
/// JSON帮助类
/// 
public static class JsonHelper
{
    /// 
    /// 1.JSON序列化 (将对象转为JSON串)
    /// 
    /// 
    /// 
    /// 返回JSON串
    public static string JsonSerializer(T t)
    {

//方法一:
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
MemoryStream ms = new MemoryStream();
ser.WriteObject(ms, t);
string jsonString = Encoding.UTF8.GetString(ms.ToArray());
ms.Close();
return jsonString;
//方法二:
DataContractJsonSerializer json = new DataContractJsonSerializer(obj.GetType());
using (MemoryStream stream = new MemoryStream())
{
json.WriteObject(stream, obj);
string szJson = Encoding.UTF8.GetString(stream.ToArray());
return szJson;
}


    }


/// /// JSON反序列化 (将JSON 转为对象) /// /// /// /// 返回T类型的对象 public static T JsonDeserialize(string jsonString) { DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T)); MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString)); T obj = (T)ser.ReadObject(ms); return obj; } }

把上述代码方法新建class类中,在项目中直接引用即可