[英]Ignore Certain Properties when Deserializing Json String
反序列化json字符串時如何忽略某些屬性。
說我有一個字符串
{"Id": 123, "name":"Test", "Description":"desc123ds"}
和具有相同屬性的類。 在某些情況下,我不想返回“ Id”。
我嘗試了一個自定義的ContractResolver,但是它唯一要做的就是設置默認值,並且該屬性仍然存在於json字符串中。
public class CoreJsonContractResolver<T> : DefaultContractResolver
{
public static CoreJsonContractResolver<T> Instance { get; } = new CoreJsonContractResolver<T>();
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
var property = base.CreateProperty(member, memberSerialization);
if(property.DeclaringType == typeof(T))
{
if (property.PropertyName == "Id")
property.Ignored = true;
}
return property;
}
}
編輯:之所以不使用[JsonIgnore]屬性,是因為我僅在某些情況下才需要忽略屬性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.