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?
-
1You'll need a custom contract resolver. This one seems like it should work: Custom Json Serializer to serialize and deserialize all properties by ignoring the class attributes.dbc– dbc2017-09-22 09:48:13 +00:00Commented Sep 22, 2017 at 9:48
-
Possible duplicate of Custom Json Serializer to serialize and deserialize all properties by ignoring the class attributesdbc– dbc2017-09-22 18:40:05 +00:00Commented Sep 22, 2017 at 18:40
Add a comment
|
1 Answer
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.