代码:
/// <summary>
/// 序列化对象
/// </summary>
/// <typeparam name="T">对象类型</typeparam>
/// <param name="value">对象实例</param>
/// <returns></returns>
public static string Serialize<T>(T value)
{
string result = string.Empty;
using (MemoryStream stream = new MemoryStream())
{
DataContractJsonSerializerSettings serializerSettings = new DataContractJsonSerializerSettings
{
UseSimpleDictionaryFormat = true
};
DataContractJsonSerializer ser = new DataContractJsonSerializer(value.GetType(), serializerSettings);
ser.WriteObject(stream, value);
stream.Position = 0;
StreamReader reader = new StreamReader(stream, Encoding.UTF8);
result = reader.ReadToEnd();
}
return result;
}
/// <summary>
/// 反序列化
/// </summary>
/// <typeparam name="T">对象类型</typeparam>
/// <param name="value">对象实例</param>
/// <returns></returns>
public static T Deserialize<T>(string value)
{
using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(value)))
{
DataContractJsonSerializerSettings serializerSettings = new DataContractJsonSerializerSettings
{
UseSimpleDictionaryFormat = true
};
DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(T), serializerSettings);
object objResponse = jsonSerializer.ReadObject(stream);
return (T)objResponse;
}
}
调用示例:
创建一个 测试类
public class MyClass
{
public string Id { get; set; }
public string Name { get; set; }
}
调用
static void Main(string[] args)
{
MyClass myClass1 = new MyClass();
myClass1.Id = "001";
myClass1.Name = "Test";
string str = Serialize(myClass1);
Console.WriteLine(str);
MyClass myClass2 = Deserialize<MyClass>(str);
Console.WriteLine();
}