【问题标题】:How to omit get-only properties only when [JsonProperty] attribute is not set on it?仅当未设置 [JsonProperty] 属性时如何省略 get-only 属性?
【发布时间】:2016-09-11 17:46:18
【问题描述】:

我在我的项目中使用 Json.Net。 我需要找到一个解决方案,其中只有在未设置属性 [JsonProperty] 时才会对 get-only 属性进行序列化。

public class Example
{
    [JsonProperty]
    public string ThisPropertyHasToBeSerialized {get;}

    public string ThisPropertyHasToBeSkipped {get;}
}

我在以下位置找到了部分答案: Is there a way to ignore get-only properties in Json.NET without using JsonIgnore attributes? 但是我想留下一个机会,以便在需要时序列化 get-only 属性。 我正在考虑像这样在 CreateProperty 函数中实现它

public class CustomContractResolver : DefaultContractResolver
{
    public static readonly CustomContractResolver Instance = new CustomContractResolver();

    protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
    {
        JsonProperty property = base.CreateProperty(member, memberSerialization);

        if(property.Writable||????????????)return property;
        else ?????  
    }
}

有没有办法检查是否在属性([JsonProperty])上设置了 json 属性,但不是[JsonIgnore]? 谢谢。

【问题讨论】:

    标签: c# json.net


    【解决方案1】:

    你可以像这样实现你的解析器:

    public class CustomContractResolver : DefaultContractResolver
    {
        public static readonly CustomContractResolver Instance = new CustomContractResolver();
    
        protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
        {
            JsonProperty property = base.CreateProperty(member, memberSerialization);
    
            // Ignore get-only properties that do not have a [JsonProperty] attribute
            if (!property.Writable && member.GetCustomAttribute<JsonPropertyAttribute>() == null)
                property.Ignored = true;
    
            return property;
        }
    }
    

    小提琴:https://dotnetfiddle.net/4oi04N

    【讨论】:

    • 太棒了。这就是我需要的。非常感谢。
    • 没问题。很高兴我能帮上忙。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-06
    • 1970-01-01
    相关资源
    最近更新 更多