为什么 JsonConverter 会忽略 WriteIndented 选项?

Why is JsonConverter ignoring the WriteIndented option?

我创建了一个新的 .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 上可用的方法,似乎没有一种方法可以将空格添加到正在写入的字符串中。所以我不认为这是错误的。

It occurred to me that I might actually be required to do the indenting myself since I'm implementing a serializer. But I looked at the methods available on Utf8JsonWriter, and there doesn't appear to be a method that adds whitespace to the string being written. So I don't think that's what's wrong.

我觉得确实是这样。 Utf8JsonWriter 有另一个可用的构造函数,它采用 JsonWriterOptions 的实例。所以你的主要功能可能是这样的:

public static void Main(string[] args)
{
    var options = new JsonWriterOptions { Indented = true };

    using (var fs = new FileStream("output.json", FileMode.Create, FileAccess.Write, FileShare.None))
    using (var writer = new Utf8JsonWriter(fs, options))
    {
        JsonSerializer.Serialize(writer, new C());
    }
}