I have a question concerning NewtonSoft Json.Net Serialization. I have searched around but have not been able to find a solution. There are some question in SO that resemble this one by the title, but none present this scenario.
What i need is to prevent certain objects from being serialized under certain conditions.
Example: Given this class:
class A
{
B b;
}
We can prevent B from being serialized by writing:
class A
{
B b;
public bool ShouldSerializeb()
{
return false; //validate the condition you want.
}
}
But if we have multiple Bs, we end up having to write a function for each one:
class A
{
B b;
B bb;
B bbb;
public bool ShouldSerializeb()
{
return false; //validate the condition you want.
}
public bool ShouldSerializebb()
{
return false; //validate the condition you want.
}
public bool ShouldSerializebbb()
{
return false; //validate the condition you want.
}
}
There is another way: Use a Contract resolver
public class ShouldSerializeContractResolver : DefaultContractResolver
{
public new static readonly ShouldSerializeContractResolver Instance
= new ShouldSerializeContractResolver();
protected override JsonProperty CreateProperty(MemberInfo member,
MemberSerialization memberSerialization)
{
JsonProperty property = base.CreateProperty(member, memberSerialization);
if (property.PropertyType == typeof(B))
{
property.ShouldSerialize =
instance =>
{
if (instance == null)
return false;
// The problem is that "instance" here is A and not B
// preventing the necessary validation
return false; //validate the condition you want.
};
}
return property;
}
}
Questions:
Is there a way to have "instance be "B" in order to validate its internals?
Is there a way to write the function to validate the object itself and not the member? Something like this:
class B
{
public bool ShouldSerialize()
{
return false; //validate the condition you want.
}
}
Thank you (I probably should post this on github, but we are so used to concentrate question in SO)