Home > Software design >  How to add indentation to JSON string to fix formatting using JsonSerializer?
How to add indentation to JSON string to fix formatting using JsonSerializer?

Time:09-20

A web service is sending me a JSON string. It contains a valid JSON string, but it is poorly formatted. Is there a way I can format it to better display it on the screen?

I was hoping to apply something like this:

JsonSerializerOptions() { WriteIndented = true }

, but I can't find the API to do it... Any advice? Thanks.

CodePudding user response:

For your json you can use just one line of the code

  1. Using new JsonNode
string formattedJson = System.Text.Json.Nodes.JsonNode.Parse(json).ToString();
  1. Using traditional JsonDocument
string formattedJson = System.Text.Json.JsonSerializer
.Serialize( JsonDocument.Parse(json), 
new JsonSerializerOptions() { WriteIndented = true });

In both cases result is the same

{
  "Sound": true,
  "Volume": 80,
  "Indexing": true,
  "Settings": [
    {
      "Item1": {
        "Key": 1,
        "Value": 1
      },
      "Item2": 1,
      "Item3": 0,
      "Item4": 1,
      "Item5": 0,
      "Item6": -1,
      "Item7": false
    },
    {
      "Item1": {
        "Key": 1,
        "Value": 2
      },
      "Item2": 2,
      "Item3": 0,
      "Item4": 1,
      "Item5": 1,
      "Item6": 2,
      "Item7": true
    },
    {
      "Item1": {
        "Key": 3,
        "Value": 2
      },
      "Item2": 1,
      "Item3": 0,
      "Item4": 2,
      "Item5": 2,
      "Item6": 3,
      "Item7": false
    },
    {
      "Item1": {
        "Key": 3,
        "Value": 3
      },
      "Item2": 1,
      "Item3": 0,
      "Item4": 1,
      "Item5": 0,
      "Item6": 4,
      "Item7": false
    }
  ]
}

CodePudding user response:

var jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(object, Formatting.Indented);

could work, but could really use more information.

  • Related