Imagine I need to unindent some raw JSON (for example, for error messages and logging). There is no simple way to do that; instead, I ended up writing the following, which seems a bit clunky:
```C#
public static string ChangeIndentation(string value, bool indented)
{
using (var stream = new MemoryStream())
{
var options = new JsonWriterOptions { Indented = indented };
using (var writer = new Utf8JsonWriter(stream, options))
{
using var document = JsonDocument.Parse(value);
document.WriteTo(writer);
}
stream.Position = 0;
using (var reader = new StreamReader(stream))
return reader.ReadToEnd();
}
}
### Proposal
```C#
namespace System.Text.Json
{
partial class JsonDocument
{
public override string ToString() => ToString(indented: true);
public string ToString(bool indented);
}
}
C#
public static string ChangeIndentation(string value, bool indented)
{
using var document = JsonDocument.Parse(value);
return document.ToString(indented);
}
The idea of seeing document.ToString(true) all over the place doesn't thrill me. How about changing the bool param to a JsonWriterOptions, then you'll end up with something like document.ToString(new JsonWriterOptions{ Indented=true }) which is longer but at least tells you what's going on more clearly. It'll also allow any future writer options to be set without adding to the api surface.
Not really sure how I feel about it, but it seems like ToString(string format) should be considered to keep consistency with everything else.
Have you tried the following?
public static string ChangeIndentation(string value)
{
JsonNode node = JsonNode.Parse(value);
return node.ToJsonString();
}
However I assume using the one you propose with JsonDocument would perform better since its read-only.
Most helpful comment
The idea of seeing
document.ToString(true)all over the place doesn't thrill me. How about changing the bool param to a JsonWriterOptions, then you'll end up with something likedocument.ToString(new JsonWriterOptions{ Indented=true })which is longer but at least tells you what's going on more clearly. It'll also allow any future writer options to be set without adding to the api surface.