When using Newtonsoft. Json to serialize objects, we can avoid few properties from being included in the output for some use case and the same property be included in the serialized output in other cases.
There's a feature in the Newtonsoft.Json.NET library, that lets us determine at runtime whether or not to serialize a particular property of a class / object. During the process of creating a class, we have to include a public method named ShouldSerialize{MemberName} returning a boolean value.
Json.NET will call that method during serialization to determine whether or not to serialize the corresponding property of the class. If this method returns true, the property will be serialized; otherwise, it will be ignored.
The following illustration shows how this can be achieved.
The following is a data definition / class that may be serialized using Newtonsoft.Json.Net
public class AuthTypeClaimMapViewModel
{
[JsonIgnore]
public bool? _canSerializeName { get; set; }
public bool ShouldSerializeAuthTypeName()
{
return _canSerializeName.HasValue ? _canSerializeName.Value : true;
}
public string AuthTypeId { get; set; }
public string AuthTypeName { get; set; }
public string ClaimMap { get; set; }
}
The following is one of the use case that will be using the ignored property to control the serialization of the AuthTypeName property
[HttpPost]
[AllowAnonymous]
public ActionResult MySettings(Listcoll, LDAPEndpointConfigurations ldapConfig)
{
coll.ForEach(c =>
{
c._canSerializeName = false;
});
var authTypeModel = Newtonsoft.Json.JsonConvert.SerializeObject(coll);
var ldapConfigs = Newtonsoft.Json.JsonConvert.SerializeObject(ldapConfig);
return View();
}
HTH
Comments
Post a Comment