I have used custom json serialization for a particular API call. But it overrides the global format. I need to reset this serialization after this API call or at the beginning of all other API calls.
public class ShouldSerializeContractResolver : CamelCasePropertyNamesContractResolver
{
private List<Serializable> _serializables;
public ShouldSerializeContractResolver(List<Serializable> serializable)
{
_serializables = serializable;
}
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
JsonProperty property = base.CreateProperty(member, memberSerialization);
foreach (var item in _serializables)
{
if (item.ObjectType.Contains(property.DeclaringType) && !item.Serialize.Contains(property.PropertyName))
{
property.ShouldSerialize =
instance =>
{
return false;
};
}
}
return property;
}
}
And I called this serializer from API controller directly as shown below:
var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
List<Serializable> serializableList = new List<Serializable>(); // Model class for storing list of Model classes and corresponding serializable objects as string
List<Type> listObjectType = new List<Type>();
List<string> serialize = new List<string>();
listObjectType.Add(typeof(ModelClassName));
serialize.Add("classObject1");
serialize.Add("classObject2");
serializableList.Add(new Serializable
{
Serialize = serialize,
ObjectType = listObjectType
});
json.SerializerSettings.ContractResolver = new ShouldSerializeContractResolver(serializableList); // This is where the serializer is modified