我遇到问题,我的JSON对象不包含C#对象(DataMember)中可用的所有属性。
在反序列化JSON时,有什么方法可以忽略缺少的属性
/// <summary>
/// Deserializes a stream that contains a json text into an object.
/// </summary>
/// <typeparam name="T">The type of the object to be deserialized into.</typeparam>
/// <param name="stream">The stream that contains the json text representation of the object.</param>
/// <returns>A deserialized object.</returns>
public static T DeserializeJson<T>(Stream stream) where T : class
{
DataContractJsonSerializerSettings settings = new DataContractJsonSerializerSettings();
settings.UseSimpleDictionaryFormat = true;
DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(T), settings);
return jsonSerializer.ReadObject(stream) as T;
}
答案 0 :(得分:0)
您可以为IsRequired
指定DataMemberAttribute
属性。
如果将其设置为false
,则如果json中缺少此成员,则反序列化不会抛出异常。
[DataMember( IsRequired = false )]
public bool ManualSessionClose { get; set; }