使用Json.NET库时,可以在序列化为字符串时指定格式,但在直接序列化为流时我无法找到此选项。我错过了什么吗?
两种序列化方法的代码如下:
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;
}
答案 0 :(得分:8)
我还没有尝试过,但如果您在设置中指定格式,我希望它没问题:
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);
}
}
(或者以类似的方式更改GetJsonSerializerSettings
。)