Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Customize identation parameter in JsonConvert.SerializeObject

Tags:

c#

.net

json.net

The default ident in Json.Net seems to be 2 spaces:

var result = JsonConvert.SerializeObject(jsonString, Formatting.Indented);

For clarity I want to change it to 4 spaces, but I don't seem to find the right way to apply the property. It seems that it exists, since I have found some similar code (direct link here):

using (JsonTextWriter jw = new JsonTextWriter(sw))
{
    jw.Formatting = Formatting.Indented;
    jw.IndentChar = ' ';
    jw.Indentation = 4;

    jw.WriteRaw(config.ToString());
}

...except that, if possible, I would preffer to avoid having to unnecessarily deal with streams in this case.

Any suggestion?

like image 983
Xavier Peña Avatar asked Dec 25 '22 13:12

Xavier Peña


1 Answers

I would create a utility class which serializes it with the right indentation, similar to how JsonConvert.SerializeObject does it:

public static class JsonConvertEx
{
    public static string SerializeObject<T>(T value)
    {
        StringBuilder sb = new StringBuilder(256);
        StringWriter sw = new StringWriter(sb, CultureInfo.InvariantCulture);

        var jsonSerializer = JsonSerializer.CreateDefault();
        using (JsonTextWriter jsonWriter = new JsonTextWriter(sw))
        {
            jsonWriter.Formatting = Formatting.Indented;
            jsonWriter.IndentChar = ' ';
            jsonWriter.Indentation = 4;

            jsonSerializer.Serialize(jsonWriter, value, typeof(T));
        }

        return sw.ToString();
    }
}

And consume it like this:

class Program
{
    static void Main(string[] args)
    {
        var anon = new { Name = "Yuval", Age = 1 };
        var result = JsonConvertEx.SerializeObject(anon);
    }
}
like image 80
Yuval Itzchakov Avatar answered Mar 30 '23 01:03

Yuval Itzchakov