C#中 JSON 序列化 与 反序列化
JSON 字符串用途广泛,不单单用在Javascript里面,在C# ,PHP ,JAVA 等开发语言也会用到,经常需要把对象序列化为JSON字符串或把JSON字符串反序列化为对象实例;
以下是C#中序列化和反序列化的例子;
首先需要引用命名空间:
using System.Runtime.Serialization.Json;
把对象序列化成字符串:
public string Serialize<T>(T obj)
{
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
using (MemoryStream stream1 = new MemoryStream())
{
ser.WriteObject(stream1, obj);
stream1.Position = 0;
StreamReader sr = new StreamReader(stream1);
//Console.WriteLine("JSON form of {0} object",typeof(T));
return sr.ReadToEnd();
}
}
反序列化对象
public T Deserialize<T>(string json) where T : class { MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json)); DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T)); T deserializedObj = ser.ReadObject(ms) as T; ms.Close(); return deserializedObj; }
posted on 2018-05-24 22:50 Tencent/Tim 阅读(147) 评论(0) 编辑 收藏 举报