Last active
October 26, 2021 18:19
-
-
Save MrBogomips/9adb4e8d2fa329c4a500e2b218f1dbcb to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static class JsonUtils | |
{ | |
/// <summary> | |
/// Indent a string containing a valid Json | |
/// </summary> | |
/// <param name="json"></param> | |
/// <returns></returns> | |
/// <exception cref="ArgumentNullException"></exception> | |
public static async Task<string> GetIndentedAsync(string json) | |
{ | |
if (json is null) throw new ArgumentNullException(nameof(json)); | |
var jsonOpts = new JsonWriterOptions() | |
{ | |
Indented = true, | |
SkipValidation = true, | |
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping | |
}; | |
var buffer = new ArrayBufferWriter<byte>(); | |
using var jsonDoc = JsonDocument.Parse(json); | |
await using var jsonWriter = new Utf8JsonWriter(buffer, jsonOpts); | |
jsonDoc.WriteTo(jsonWriter); | |
await jsonWriter.FlushAsync(); | |
return Encoding.UTF8.GetString(buffer.WrittenMemory.ToArray()); | |
} | |
/// <inheritdoc cref="GetIndentedAsync"/> | |
public static string GetIndented(string json) => GetIndentedAsync(json).GetAwaiter().GetResult(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment