简体   繁体   中英

Customize identation parameter in JsonConvert.SerializeObject

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM