When serializing an object using Newtonsoft.Json, is there a way to stop indentation of the serialized values after a given depth?
For example given the object in Listing 1, is there a way to subclass the JsonConverter
or JsonWriter
to indent only up to a certain level so that instead of the output in Dump 1, you get that in Dump 2 or Dump 3?
Listing 1
var items = new[] {
new { Name = "John",
Age = 5,
Address = new { Home = "No. 123, Oak Street", Email = "[email protected]" },
Extra = new { Serials = new[] { 20, 30, 40, 50 } }
},
new { Name = "Jean",
Age = 2,
Address = new { Home = "No. 321, Cliff Road", Email = "[email protected]" },
Extra = new { Serials = new[] { 25, 35, 45, 55 } }
}
};
Dump 1: Fully Indented
[
{
"Name": "John",
"Age": 5,
"Address": {
"Home": "No. 123, Oak Street",
"Email": "[email protected]"
},
"Extra": {
"Serials": [
20,
30,
40,
50
]
}
},
{
"Name": "Jean",
"Age": 2,
"Address": {
"Home": "No. 321, Cliff Road",
"Email": "[email protected]"
},
"Extra": {
"Serials": [
25,
35,
45,
55
]
}
}
]
Dump 2: Two levels deep
[
{
"Name": "John",
"Age": 5,
"Address": { "Home": "No. 123, Oak Street", "Email": "[email protected]" },
"Extra": { "Serials": [ 20, 30, 40, 50 ] }
},
{
"Name": "Jean",
"Age": 2,
"Address": { "Home": "No. 321, Cliff Road", "Email": "[email protected]" },
"Extra": { "Serials": [ 25, 35, 45, 55 ] }
}
]
Dump 3: Three levels deep
[
{
"Name": "John",
"Age": 5,
"Address": {
"Home": "No. 123, Oak Street",
"Email": "[email protected]"
},
"Extra": {
"Serials": [ 20, 30, 40, 50 ]
}
},
{
"Name": "Jean",
"Age": 2,
"Address": {
"Home": "No. 321, Cliff Road",
"Email": "[email protected]"
},
"Extra": {
"Serials": [ 25, 35, 45, 55 ]
}
}
]
question from:
https://stackoverflow.com/questions/65557528/how-do-you-limit-indentation-depth-when-serializing-with-newtonsoft-json