I only want the first depth level of an object (I do not want any children). I am willing to use any library available. Most libraries will merely throw an exception when the recursion depth is reached, instead of just ignoring. If this isn’t possible, is there a way to ignore serialization of certain members given a certain datatype?
Edit:
Let’s say I have an object like so:
class MyObject
{
String name = "Dan";
int age = 88;
List<Children> myChildren = ...(lots of children with lots of grandchildren);
}
I want to remove any children (complex types even) to return an object like this:
class MyObject
{
String name = "Dan";
int age = 88;
List<Children> myChildren = null;
}
This is possible in Json.NET using some coordination between the
JsonWriterand the serializer’sContractResolver.A custom
JsonWriterincrements a counter when an object is started and then decrements it again when it ends.A custom
ContractResolverapplies a specialShouldSerializepredicate on all properties that will be used to verify the current depth.The following method shows how these two custom classes work together.
The following test code demonstrates limiting the maximum depth to 1 and 2 levels respectively.