79

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?

1
  • Which classes are you using? JSON.NET provides a few different options. Commented Oct 30, 2011 at 18:55

2 Answers 2

129

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

Sign up to request clarification or add additional context in comments.

1 Comment

The various JsonConvert.Serialize* methods also take Formatting as the second argument.
18

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 });

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.