1

I use Json.Net in my project. I need to find a solution where get-only properties do not serialize only if attribute [JsonProperty] is not set.

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

    public string ThisPropertyHasToBeSkipped {get;}
}

I found a partial answer to it at: Is there a way to ignore get-only properties in Json.NET without using JsonIgnore attributes? But I want to leave an opportunity for get-only properties to be serialized in case it is needed. I am thinking of implementing it in CreateProperty function like this

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 ?????  
    }
}

Is there a way to check if json Attribute was set on a property ([JsonProperty]) but not [JsonIgnore]? Thanks.

Community
  • 1
  • 1

1 Answers1

0

You can implement your resolver like this:

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;
    }
}

Fiddle: https://dotnetfiddle.net/4oi04N

Brian Rogers
  • 125,747
  • 31
  • 299
  • 300