2

I am working on a ASP.NET WebApi project. I have a model class that has a property that I don't want to serialize in public calls. For this purpose I am usin [JsonIgnore] for that property and it is excluded from jsons as expected. Now in a [Authorize] controller method I want to serialize object with all properties, even the one that excluded by [JsonIgnore]. Any idae?

2

1 Answer 1

0

You can create your own resolver which will include properties that are marked with [JsonIgnore] attribute:

public class IncludeIgnoredMembersContractResolver : DefaultContractResolver
{
    protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
    {
        var jsonProperty = base.CreateProperty(member, memberSerialization);

        var jsonIgnoreAttribute = (member as PropertyInfo)?.GetCustomAttribute<JsonIgnoreAttribute>();

        if (jsonIgnoreAttribute is not null)
        {
            jsonProperty.Ignored = false;
        }

        return jsonProperty;
    }
}

Then you can set it up in options whenever you want to serialize ignored members:

var result = JsonConvert.DeserializeObject<MyResultModel>(content, new JsonSerializerSettings
{
    ContractResolver = new IncludeIgnoredMembersContractResolver(),
});

In case you still want to ignore the property then you can use default contract resolver and it will work as per default.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.