简体   繁体   English

反序列化Json字符串时忽略某些属性

[英]Ignore Certain Properties when Deserializing Json String

How do I ignore certain properties when deserializing a json string. 反序列化json字符串时如何忽略某些属性。

Say I have a string 说我有一个字符串

{"Id": 123, "name":"Test", "Description":"desc123ds"}

and a class with the same properties. 和具有相同属性的类。 In some cases I don't want to return "Id". 在某些情况下,我不想返回“ Id”。

I have tried a custom ContractResolver but the only thing it does is sets the default value and the property remains present in the json string. 我尝试了一个自定义的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;
        }
    }

EDIT: The reason why I didn't use [JsonIgnore] property is because I need to ignore properties only in certain cases. 编辑:之所以不使用[JsonIgnore]属性,是因为我仅在某些情况下才需要忽略属性。

看看JsonIgnore 属性 ,看看这篇文章

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM