摘要:[C#] 使用 DataContractJsonSerializer 序列化 反序列化
為了怕自己忘記 決定記錄在這
序列化
public string Serialize<T>(T obj)
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
using(MemoryStream stream = new MemoryStream())
{
serializer.WriteObject(stream, obj);
byte[] data = stream.ToArray();
string json = System.Text.Encoding.UTF8.GetString(data,0, data.Length);
}
return json;
}
反序列化
public T Deserialize<T>(string json)
{
T obj = default(T);
DataContractJsonSerializer deserializer = new DataContractJsonSerializer(typeof(T));
using(MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(json)))
{
obj = (T)deserializer.ReadObject(stream);
}
return obj;
}