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;
}
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With