Can Json.NET serialize to stream with Formatting?

℡╲_俬逩灬. 提交于 2019-12-08 15:55:13

问题


When using Json.NET library, you can specify formatting when you are serialising to string, but I can't find this option when serialising directly to stream. Am I missing something?

The code for the two serialisation methods is as follows:

public static string Serialize(MyObject obj)
{
    JsonSerializerSettings settings = GetJsonSerializerSettings();
    return JsonConvert.SerializeObject(obj, Formatting.Indented, settings);
}

public static void SerializeToStream(MyObject obj, Stream stream)
{
    var serializer = JsonSerializer.Create(GetJsonSerializerSettings());

    using (var sw = new StreamWriter(stream))
    using (var jsonTextWriter = new JsonTextWriter(sw))
    {
        serializer.Serialize(jsonTextWriter, obj);
    }
}

private static JsonSerializerSettings GetJsonSerializerSettings()
{
    JsonSerializerSettings settings = new JsonSerializerSettings
    {
        Converters = new List<JsonConverter>
        {
            new StringEnumConverter()
        }
    };
    return settings;
}

回答1:


I haven't tried it, but I'd expect it to be fine if you specify the formatting in the settings:

public static void SerializeToStream(MyObject obj, Stream stream)
{
    var settings = GetJsonSerializerSettings();
    settings.Formatting = Formatting.Indented;
    var serializer = JsonSerializer.Create(settings);

    using (var sw = new StreamWriter(stream))
    using (var jsonTextWriter = new JsonTextWriter(sw))
    {
        serializer.Serialize(jsonTextWriter, obj);
    }
}

(Or change GetJsonSerializerSettings in a similar way, of course.)



来源:https://stackoverflow.com/questions/26659688/can-json-net-serialize-to-stream-with-formatting

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