Customize identation parameter in JsonConvert.SerializeObject

梦想与她 提交于 2019-12-12 16:53:43

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/33100164/customize-identation-parameter-in-jsonconvert-serializeobject

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!