DataContractJsonSerializer serializer = new DataContractJsonSerializer(item.GetType());
using (MemoryStream ms = new MemoryStream()) {
serializer.WriteObject(ms, item);
StringBuilder sb = new StringBuilder();
sb.Append(Encoding.UTF8.GetString(ms.ToArray()));
return sb.ToString();
}
}
/// <summary> /// Json反序列化,用于接收客户端Json后生成对应的对象 /// </summary> public static T FromJsonTo<T>(this string jsonString) {
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
T jsonObject = (T)ser.ReadObject(ms);
ms.Close();
return jsonObject;
}
实体类
[DataContract] public class TestObj { [DataMember] public string make { get; set; } [DataMember] public string model { get; set; } [DataMember] public int year { get; set; } [DataMember] public string color { get; set; } }