1

Say I have an async web api 2 controller method returning a Created ActionResult like:

return Created(new Uri(Request.RequestUri + "/" + Item.Id), Item);

Item has a property ItemDescriptions which I would like to truncate on response. How do I define serialization for a Created Web Api response like this?

I tried creating a custom resolver like:

public class ItemContractResolver: CamelCasePropertyNamesContractResolver
{
    protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
    {
        var property = base.CreateProperty(member, memberSerialization);

        if (property.PropertyName == "ItemDescriptions")
        {
            property.ShouldSerialize = i => false;
            property.ShouldDeserialize = i => false;
        }
        return property;
    }
}

Which I later set in the Controller constructor like:

        var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
        json.SerializerSettings.ContractResolver = new ItemContractResolver();

But that sadly does not work and the ItemDescriptions property is still serialized.

1 Answer 1

1

JsonProperty.PropertyName is the serialized name of the property. Since you are inheriting from CamelCasePropertyNamesContractResolver it will be "itemDescriptions".

Instead, check against JsonProperty.UnderlyingName which is the name of the underlying member or parameter:

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

    if (typeof(Item).IsAssignableFrom(property.DeclaringType) 
        && property.UnderlyingName == nameof(Item.ItemDescriptions))
    {
        property.Ignored = true;
    }

    return property;
}

Notes -

  • Setting JsonProperty.Ignored should be simpler and slightly more performant than setting ShouldSerialize and ShouldDeserialize delegates.

  • Using nameof avoids hardcoding the property name.

  • It seems wise to check that the type being serialized inherits from Item in case a property named ItemDescriptions is later added to some unrelated type.

  • You could always just mark the property with [JsonIgnore] - unless the type is in some external library and cannot be modified.

Sample working .Net fiddle.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, thats exactly what I have been looking for.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.