[DataContract] public class User { [DataMember] public string Name { get; set; } [DataMember] public int Age { get; set; } public User() { } public User(string newName, int newAge) { Name = newName; Age = newAge; } }
//转化成Json数据 public static string WriteFromObject() { User user = new User("Bob", 42); MemoryStream ms = new MemoryStream(); DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(User)); ser.WriteObject(ms, user); byte[] json = ms.ToArray(); ms.Close(); return Encoding.UTF8.GetString(json, 0, json.Length); } //Json转化成类 public static User ReadToObject(string json) { User deserializedUser = new User(); MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json)); DataContractJsonSerializer ser = new DataContractJsonSerializer(deserializedUser.GetType()); deserializedUser = ser.ReadObject(ms) as User; ms.Close(); return deserializedUser; }