在使用System.Runtime.Serialization.Json的DataContractJsonSerializer进行序列化的时候,我们可能只需要序列化某些字段或者属性,我个时候我们需要人工指明,这里举一个例子:
[DataContract]//这个不能少
public class DemoContact
{
[DataMember]//不需要排除的必须这样指明
public string Name;
[IgnoreDataMember]//需要排除的这样指明,可以省略
public int Age;
[DataMember]
public string Address { set; get; }
public string Company { set; get; }
}
附两个序列化和反序列化的函数:
/// <summary>
/// 序列化
/// 将对象转化为字符串
/// </summary>
public static string Serialize(object objectToSerialize)
{
if (objectToSerialize == null) return "";
using (MemoryStream ms = new MemoryStream())
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(objectToSerialize.GetType());
serializer.WriteObject(ms, objectToSerialize);
ms.Position = 0;
using (StreamReader reader = new StreamReader(ms))
{
return reader.ReadToEnd();
}
}
}
/// <summary>
/// 反序列化
/// Json字符串转化为对象
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="jsonString"></param>
/// <returns></returns>
public static T Deserialize<T>(string jsonString)
{
using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString)))
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
return (T)serializer.ReadObject(ms);
}
}
用上面的序列化函数序列化一个空白的DemoContact后得到的字符串如下:
"{"Address":null,"Name":null}"
可以看到,只有用[DataMember]指明的字段或者属性被序列化了。
达叔傻乐(darwin.zuo@163.com)
网友评论