I am having trouble formatting my serialized C# objects using System.Text.Json.Serialization. Here are some example objects similar to what I am serializing:
public class school
{
public string school {get;set;}
public string address {get;set;}
public List<classroom> classes {get;set;}
}
public class classroom
{
public string topic {get;set;}
public int room {get;set;}
public List<student> students {get;set;}
}
public class student
{
public string name {get;set;}
public int age {get;set;}
public double grade {get;set;}
public List<pet>? pets {get;set;}
}
public class pet
{
public string name {get;set;}
public string type {get;set;}
}
And here is the way I would like to have the json formatted: I think I am trying to have the JsonSerializerOptions set to not WriteIndented for most of my objects, but I do want a newline for each object in an array. Basically, I want every "{" to start a new line.
{"school": "fake elementary", "address": "1234 Fake Ln.", "classes":[
{"class": "history", "room": 21, "students": [
{"name": "henry", "age": 8, "grad": 0.85, "pets": [
{"type": "dog", "name": "kitty"}
]},
{"name": "jill", "age": 9, "grad": 0.95, "pets": [
{"type": "cat", "name": "pooch"}
]},
{"name": "andy", "age": 8, "grad": 0.75},
{"name": "mary", "age": 9, "grad": 0.85},
{"name": "sally", "age": 8, "grad": 0.45}
]},
{"class": "math", "room": 15, "students": [
{"name": "henry", "age": 8, "grad": 0.95},
{"name": "jill", "age": 9, "grad": 0.75},
{"name": "andy", "age": 8, "grad": 0.45},
{"name": "mary", "age": 9, "grad": 0.95},
{"name": "sally", "age": 8, "grad": 0.85}
]}
]}
Unfortunately, I can either serialize the school object with or without WriteIndented and that applies to all of its objects. Is there a way around this? I am trying to see if I need to make a converter that inherits from JsonConverter, but I haven't been able to figure this out. Otherwise, I could just write out my serialized json without any Indentation, then modify the document to look the way I want it, but this does not seem like the right approach.