【发布时间】:2020-10-30 17:56:27
【问题描述】:
我创建了一个新的 .NET Core 控制台应用并将 Program.cs 文件更改为以下内容:
using System;
using System.IO;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace JsonSerialization
{
public static class Program
{
public static void Main(string[] args)
{
var options = new JsonSerializerOptions {WriteIndented = true};
using (var fs = new FileStream("output.json", FileMode.Create, FileAccess.Write, FileShare.None))
using (var writer = new Utf8JsonWriter(fs))
{
JsonSerializer.Serialize(writer, new C(), options);
}
}
}
[JsonConverter(typeof(S))]
class C
{}
class S: JsonConverter<C>
{
public override C Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
throw new NotImplementedException();
}
public override void Write(Utf8JsonWriter writer, C value, JsonSerializerOptions options)
{
writer.WriteStartObject();
writer.WriteString("a", "b");
writer.WriteString("c", "d");
writer.WriteEndObject();
}
}
}
当我运行程序时,会在包含可执行文件的目录中创建一个名为“output.json”的文件,正如预期的那样。文件内容如下:
{"a":"b","c":"d"}
我希望看到这个:
{
"a": "b",
"c": "d"
}
提供的选项设置 (WriteIndented = true) 将被忽略。这是为什么呢?
我已经通过程序进行了调试,并验证了我在 S 中的 Write() 实现正在被调用(方法中设置的断点被命中)并且我传入的 JsonSerializerOptions 是方法中可用的(或者至少,它的 WriteIndented 设置为 true,就像我传入的一样)。
我突然想到,由于我正在实现序列化程序,因此实际上可能需要我自己进行缩进。但是我查看了 Utf8JsonWriter 上可用的方法,似乎没有一种方法可以将空格添加到正在写入的字符串中。所以我认为这不是问题所在。
【问题讨论】:
标签: c# json serialization .net-core system.text.json