需要序列化的对象的类需要添加一些特性来支持序列化:
[DataContract]
class User
{
[DataMember]
public string Name { get; set; }
[DataMember]
public int Age { get; set; }
}
使用 DataContractJsonSerializer 把对象转成 JSON,以及把 JSON 转成对象:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Json;
using System.Text;
namespace MyApp.Utils
{
static class JsonUtil
{
public static string ToJson<T>(this T obj) where T : class
{
DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(obj.GetType());
using (var stream = new MemoryStream())
{
jsonSerializer.WriteObject(stream, obj);
return Encoding.UTF8.GetString(stream.ToArray());
}
}
public static T ToObject<T>(this string json) where T : class
{
DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(T));
using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(json)))
{
return jsonSerializer.ReadObject(stream) as T;
}
}
}
}
测试代码
User user = new User
{
Name = "Tom",
Age = 23
};
string json = user.ToJson();
Console.WriteLine(json);
user = json.ToObject<User>();
user.Name = "Jerry";
user.Age = 42;
Console.WriteLine(user.ToJson());