18

I am using this code to serialize the users into json text file.

if (File.Exists(path))
{
    using (var file = File.CreateText(path))
    {
        var serializer = new JsonSerializer();
        serializer.Serialize(file, this.users);
    }
}

This is the result that I get :

[output]

How can I get a result like this :

[pretty-print]

Art
  • 285
  • 1
  • 3
  • 11

2 Answers2

25

Set the formatting on the serializer to Indented.

var serializer = new JsonSerializer();
serializer.Formatting = Formatting.Indented;
serializer.Serialize(file, this.users);    
Jonathon Chase
  • 9,396
  • 21
  • 39
17

Use this instead :

if (File.Exists(path))
{
    using (var file = File.CreateText(path))
    {
        var json = JsonConvert.SerializeObject(this.users, Formatting.Indented);
        file.Write(json);
    }
}
Xiaoy312
  • 14,292
  • 1
  • 32
  • 44