[英]DeSerialize JSON into C# Object: How to Handle Missing properties
I have a problem, my JSON object does not contain all the properties which are available in C# object (DataMember). 我有一个问题,我的JSON对象没有包含C#对象(DataMember)中可用的所有属性。
Is there any way I can ignore missing properties while deserializing JSON 有什么办法可以在反序列化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;
}
You can specify IsRequired
property for DataMemberAttribute
. 您可以为
DataMemberAttribute
指定IsRequired
属性。 If you set it to false
, deserialisation won't throw exception if this member is missing in your json. 如果将其设置为
false
,则在json中缺少该成员时,反序列化不会引发异常。
[DataMember( IsRequired = false )]
public bool ManualSessionClose { get; set; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.