I am using Json.Net to serialize XML into JSON. When I write the serialized string to a file it all comes in a single line. How do I get it to actually look like Json with the usual tabs and indentation?
2 Answers
Set the JSON writer Formatting property to Formatting.Indented:
jsonWriter.Formatting = Formatting.Indented;
The JsonConvert.Serialize* methods also have overloads that take a Formatting enum (thanks John Flatness).
Documentation: Serialize an Object
1 Comment
John Flatness
The various
JsonConvert.Serialize* methods also take Formatting as the second argument.For those who ask how I get formatted JSON in .NET using C# and want to see how to use it right away and one-line lovers. Here are the indented JSON string one-line codes:
There are 2 well-known JSON formatter or parsers to serialize:
Newtonsoft Json.Net version:
using Newtonsoft.Json;
var jsonString = JsonConvert.SerializeObject(yourObj, Formatting.Indented);
.Net 7 version:
using System.Text.Json;
var jsonString = JsonSerializer.Serialize(yourObj, new JsonSerializerOptions { WriteIndented = true });