user34537
user34537

Reputation:

How do I get formatted JSON in .NET using C#?

I am using .NET JSON parser and would like to serialize my config file so it is readable. So instead of:

{"blah":"v", "blah2":"v2"}

I would like something nicer like:

{
    "blah":"v", 
    "blah2":"v2"
}

My code is something like this:

using System.Web.Script.Serialization; 

var ser = new JavaScriptSerializer();
configSz = ser.Serialize(config);
using (var f = (TextWriter)File.CreateText(configFn))
{
    f.WriteLine(configSz);
    f.Close();
}

Upvotes: 383

Views: 426127

Answers (21)

Omer
Omer

Reputation: 10174

2025 Update

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

Upvotes: 31

datchung
datchung

Reputation: 4622

Here is the System.Text.Json version inspired by David Duman's answer:

private static string FormatJson(string json)
{
    var parsedJson = JsonSerializer.Deserialize<dynamic>(json);
    return JsonSerializer.Serialize(parsedJson, new JsonSerializerOptions { WriteIndented = true });
}

Upvotes: 0

anon2
anon2

Reputation: 1

using System.Text.Json;

namespace Something.Extensions;

public static class StringExtensions
{    
    static JsonSerializerOptions defaultJsonSerializerOptions = new JsonSerializerOptions { WriteIndented = true };
    public static string FormatJson(this string json, JsonSerializerOptions? options = default) => 
        JsonSerializer.Serialize<object>(JsonSerializer.Deserialize<object>(json ?? "{}")!, options ?? defaultJsonSerializerOptions);
}

usage

var r = @"
    
    {
    ""dsadsa"":""asdasd""
            }";
content = r.FormatJson(new JsonSerializerOptions { WriteIndented = true });

use case example: unknown API response without indented response

var businessId = 2;
var request = new HttpRequestMessage(HttpMethod.Get, $"http://localhost:7010/Business/{businessId}");
var client = clientFactory.CreateClient();
var responseMessage = await client.SendAsync(request);
if (responseMessage.IsSuccessStatusCode)
{
    var r = await responseMessage.Content.ReadAsStringAsync();
    content = r.FormatJson(new JsonSerializerOptions { WriteIndented = true });
}
else
{
    throw new Exception($"!IsSuccessStatusCode:{responseMessage.StatusCode}");
}

Upvotes: 0

Samia Saleem
Samia Saleem

Reputation: 76

var formattedJson = System.Text.Json.JsonSerializer.Serialize(myresponse, new JsonSerializerOptions
{
     WriteIndented = true
});
    Console.WriteLine(formattedJson);

enter image description here

Upvotes: 0

Sith2021
Sith2021

Reputation: 3716

Net Core App

var js = JsonSerializer.Serialize(obj, new JsonSerializerOptions {
             WriteIndented = true
         });

Upvotes: 68

Yola
Yola

Reputation: 19033

using System.Text.Json;
...
var parsedJson = JsonSerializer.Deserialize<ExpandoObject>(json);
var options = new JsonSerializerOptions() { WriteIndented = true };
return JsonSerializer.Serialize(parsedJson, options);

Upvotes: 7

Nemo
Nemo

Reputation: 3373

.NET 5 has built in classes for handling JSON parsing, serialization, deserialization under System.Text.Json namespace. Below is an example of a serializer which converts a .NET object to a JSON string,

using System.Text.Json;
using System.Text.Json.Serialization;

private string ConvertJsonString(object obj)
{
    JsonSerializerOptions options = new JsonSerializerOptions();
    options.WriteIndented = true; //Pretty print using indent, white space, new line, etc.
    options.NumberHandling = JsonNumberHandling.AllowNamedFloatingPointLiterals; //Allow NANs
    string jsonString = JsonSerializer.Serialize(obj, options);
    return jsonString;
}

Upvotes: 1

Andr&#233;s Fg
Andr&#233;s Fg

Reputation: 136

I have something very simple for this. You can put as input really any object to be converted into json with a format:

private static string GetJson<T> (T json)
{
    return JsonConvert.SerializeObject(json, Formatting.Indented);
}

Upvotes: 1

asherber
asherber

Reputation: 2713

Shortest version to prettify existing JSON: (edit: using JSON.net)

JToken.Parse("mystring").ToString()

Input:

{"menu": { "id": "file", "value": "File", "popup": { "menuitem": [ {"value": "New", "onclick": "CreateNewDoc()"}, {"value": "Open", "onclick": "OpenDoc()"}, {"value": "Close", "onclick": "CloseDoc()"} ] } }}

Output:

{
  "menu": {
    "id": "file",
    "value": "File",
    "popup": {
      "menuitem": [
        {
          "value": "New",
          "onclick": "CreateNewDoc()"
        },
        {
          "value": "Open",
          "onclick": "OpenDoc()"
        },
        {
          "value": "Close",
          "onclick": "CloseDoc()"
        }
      ]
    }
  }
}

To pretty-print an object:

JToken.FromObject(myObject).ToString()

Upvotes: 150

Deedz
Deedz

Reputation: 137

This worked for me. In case someone is looking for a VB.NET version.

@imports System
@imports System.IO
@imports Newtonsoft.Json
    
Public Shared Function JsonPrettify(ByVal json As String) As String
  Using stringReader = New StringReader(json)

    Using stringWriter = New StringWriter()
      Dim jsonReader = New JsonTextReader(stringReader)
      Dim jsonWriter = New JsonTextWriter(stringWriter) With {
          .Formatting = Formatting.Indented
      }
      jsonWriter.WriteToken(jsonReader)
      Return stringWriter.ToString()
    End Using
  End Using
End Function

Upvotes: 1

Max Venediktov
Max Venediktov

Reputation: 382

First I wanted to add comment under Duncan Smart post, but unfortunately I have not got enough reputation yet to leave comments. So I will try it here.

I just want to warn about side effects.

JsonTextReader internally parses json into typed JTokens and then serialises them back.

For example if your original JSON was

{ "double":0.00002, "date":"\/Date(1198908717056)\/"}

After prettify you get

{ 
    "double":2E-05,
    "date": "2007-12-29T06:11:57.056Z"
}

Of course both json string are equivalent and will deserialize to structurally equal objects, but if you need to preserve original string values, you need to take this into concideration

Upvotes: 2

Sky Sanders
Sky Sanders

Reputation: 37084

You are going to have a hard time accomplishing this with JavaScriptSerializer.

Try JSON.Net.

With minor modifications from JSON.Net example

using System;
using Newtonsoft.Json;

namespace JsonPrettyPrint
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            Product product = new Product
                {
                    Name = "Apple",
                    Expiry = new DateTime(2008, 12, 28),
                    Price = 3.99M,
                    Sizes = new[] { "Small", "Medium", "Large" }
                };

            string json = JsonConvert.SerializeObject(product, Formatting.Indented);
            Console.WriteLine(json);

            Product deserializedProduct = JsonConvert.DeserializeObject<Product>(json);
        }
    }

    internal class Product
    {
        public String[] Sizes { get; set; }
        public decimal Price { get; set; }
        public DateTime Expiry { get; set; }
        public string Name { get; set; }
    }
}

Results

{
  "Sizes": [
    "Small",
    "Medium",
    "Large"
  ],
  "Price": 3.99,
  "Expiry": "\/Date(1230447600000-0700)\/",
  "Name": "Apple"
}

Documentation: Serialize an Object

Upvotes: 333

DrBB
DrBB

Reputation: 163

For UTF8 encoded JSON file using .NET Core 3.1, I was finally able to use JsonDocument based upon this information from Microsoft: https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-how-to#utf8jsonreader-utf8jsonwriter-and-jsondocument

string allLinesAsOneString = string.Empty;
string [] lines = File.ReadAllLines(filename, Encoding.UTF8);
foreach(var line in lines)
    allLinesAsOneString += line;

JsonDocument jd = JsonDocument.Parse(Encoding.UTF8.GetBytes(allLinesAsOneString));
var writer = new Utf8JsonWriter(Console.OpenStandardOutput(), new JsonWriterOptions
{
    Indented = true
});
JsonElement root = jd.RootElement;
if( root.ValueKind == JsonValueKind.Object )
{
    writer.WriteStartObject();
}
foreach (var jp in root.EnumerateObject())
    jp.WriteTo(writer);
writer.WriteEndObject();

writer.Flush();

Upvotes: 0

Andrew Shepherd
Andrew Shepherd

Reputation: 45252

Here is a solution using Microsoft's System.Text.Json library:

static string FormatJsonText(string jsonString)
{
    using var doc = JsonDocument.Parse(
        jsonString,
        new JsonDocumentOptions
        {
            AllowTrailingCommas = true
        }
    );
    MemoryStream memoryStream = new MemoryStream();
    using (
        var utf8JsonWriter = new Utf8JsonWriter(
            memoryStream,
            new JsonWriterOptions
            {
                Indented = true
            }
        )
    )
    {
        doc.WriteTo(utf8JsonWriter);
    }
    return new System.Text.UTF8Encoding()
        .GetString(memoryStream.ToArray());
}

Upvotes: 28

Ebube
Ebube

Reputation: 483

All this can be done in one simple line:

string jsonString = JsonConvert.SerializeObject(yourObject, Formatting.Indented);

Upvotes: 35

newuser
newuser

Reputation: 317

Below code works for me:

JsonConvert.SerializeObject(JToken.Parse(yourobj.ToString()))

Upvotes: 0

Jamie Kitson
Jamie Kitson

Reputation: 4140

Using System.Text.Json set JsonSerializerOptions.WriteIndented = true:

JsonSerializerOptions options = new JsonSerializerOptions { WriteIndented = true };
string json = JsonSerializer.Serialize<Type>(object, options);

Upvotes: 9

Makeman
Makeman

Reputation: 944

You may use following standard method for getting formatted Json

JsonReaderWriterFactory.CreateJsonWriter(Stream stream, Encoding encoding, bool ownsStream, bool indent, string indentChars)

Only set "indent==true"

Try something like this

    public readonly DataContractJsonSerializerSettings Settings = 
            new DataContractJsonSerializerSettings
            { UseSimpleDictionaryFormat = true };

    public void Keep<TValue>(TValue item, string path)
    {
        try
        {
            using (var stream = File.Open(path, FileMode.Create))
            {
                //var currentCulture = Thread.CurrentThread.CurrentCulture;
                //Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;

                try
                {
                    using (var writer = JsonReaderWriterFactory.CreateJsonWriter(
                        stream, Encoding.UTF8, true, true, "  "))
                    {
                        var serializer = new DataContractJsonSerializer(type, Settings);
                        serializer.WriteObject(writer, item);
                        writer.Flush();
                    }
                }
                catch (Exception exception)
                {
                    Debug.WriteLine(exception.ToString());
                }
                finally
                {
                    //Thread.CurrentThread.CurrentCulture = currentCulture;
                }
            }
        }
        catch (Exception exception)
        {
            Debug.WriteLine(exception.ToString());
        }
    }

Pay your attention to lines

    var currentCulture = Thread.CurrentThread.CurrentCulture;
    Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
    ....
    Thread.CurrentThread.CurrentCulture = currentCulture;

For some kinds of xml-serializers you should use InvariantCulture to avoid exception during deserialization on the computers with different Regional settings. For example, invalid format of double or DateTime sometimes cause them.

For deserializing

    public TValue Revive<TValue>(string path, params object[] constructorArgs)
    {
        try
        {
            using (var stream = File.OpenRead(path))
            {
                //var currentCulture = Thread.CurrentThread.CurrentCulture;
                //Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;

                try
                {
                    var serializer = new DataContractJsonSerializer(type, Settings);
                    var item = (TValue) serializer.ReadObject(stream);
                    if (Equals(item, null)) throw new Exception();
                    return item;
                }
                catch (Exception exception)
                {
                    Debug.WriteLine(exception.ToString());
                    return (TValue) Activator.CreateInstance(type, constructorArgs);
                }
                finally
                {
                    //Thread.CurrentThread.CurrentCulture = currentCulture;
                }
            }
        }
        catch
        {
            return (TValue) Activator.CreateInstance(typeof (TValue), constructorArgs);
        }
    }

Thanks!

Upvotes: 13

Dariusz Tarczynski
Dariusz Tarczynski

Reputation: 16711

Oneliner using Newtonsoft.Json.Linq:

string prettyJson = JToken.Parse(uglyJsonString).ToString(Formatting.Indented);

Upvotes: 66

Duncan Smart
Duncan Smart

Reputation: 32058

If you have a JSON string and want to "prettify" it, but don't want to serialise it to and from a known C# type then the following does the trick (using JSON.NET):

using System;
using System.IO;
using Newtonsoft.Json;

class JsonUtil
{
    public static string JsonPrettify(string 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();
        }
    }
}

Upvotes: 163

David Duman
David Duman

Reputation: 6656

A shorter sample code for Json.Net library

private static string FormatJson(string json)
{
    dynamic parsedJson = JsonConvert.DeserializeObject(json);
    return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}

Upvotes: 246

Related Questions