I need to serialize only first level of an object by JsonConvert.SerializeObject. I've tried MaxDepth = 1, but this property is only for Deserialization.
Desired behaviour (Property Bar is missing or is null):
class Foo
{
public int First { get; set; } = 123;
public string Second { get; set; } = "smurf";
public DateTime Third { get; set; } = DateTime.Now;
public Bar Bar { get; set; } = new Bar { Fourth = 999 };
}
class Bar
{
public int Fourth { get; set; }
}
void Test(){
var foo = new Foo();
var jsonResult = JsonConvert.SerializeObject(foo);
// jsonResult:
// {
// "First": 123,
// "Second": "smurf",
// "Third": "6.4. 2020 7:16",
// }
}
How should I setup JsonConvert.SerializeObject to ignore children non-primitive objects in serialization? Many thanks.