Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pretty print using System.Text.Json for unknown object

Using System.Text.Json i can pretty print json using serialization option.

var options = new JsonSerializerOptions{ WriteIndented = true };
jsonString = JsonSerializer.Serialize(typeToSerialize, options);

However, I have string JSON and don't know the concrete type. Ho do I pretty-print JSON string?

My old code was using Newtonsoft and I could do it without serialize/deserialize

public static string JsonPrettify(this string json)
{
    if (string.IsNullOrEmpty(json))
    {
        return json;
    }

    using (var stringReader = new StringReader(json))
    using (var stringWriter = new StringWriter())
    {
        var jsonReader = new JsonTextReader(stringReader);
        var jsonWriter = new JsonTextWriter(stringWriter) { Formatting = Formatting.Indented };
        jsonWriter.WriteToken(jsonReader);
        return stringWriter.ToString();
    }
}
like image 331
LP13 Avatar asked Jan 07 '21 22:01

LP13


People also ask

How do I pretty print a JSON object?

Use json. dumps() method to prettyprint JSON properly by specifying indent and separators. The json. dumps() method returns prettyprinted JSON data in string format.

How do I pretty print a JSON string?

Use JSON. stringify(obj) method to convert JavaScript objects into strings and display it. Use JSON. stringify(obj, replacer, space) method to convert JavaScript objects into strings in pretty format.

How do I deserialize text JSON?

A common way to deserialize JSON is to first create a class with properties and fields that represent one or more of the JSON properties. Then, to deserialize from a string or a file, call the JsonSerializer. Deserialize method.

What is JSON pretty format?

Pretty printing is a form of stylistic formatting including indentation and colouring. JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write and for machines to parse and generate. The official Internet media type for JSON is application/json .


1 Answers

This works:

using System.Text.Json;
public static string JsonPrettify(this string json)
{
    using var jDoc = JsonDocument.Parse(json);
    return JsonSerializer.Serialize(jDoc, new JsonSerializerOptions { WriteIndented = true });
}
like image 155
dlumpp Avatar answered Oct 08 '22 02:10

dlumpp