自定义 JsonConverter (System.Text.Json) 产生无效 json

Custom JsonConverter (System.Text.Json) producing invalid json

这是class我要自定义序列化:

public class MyClass
{
    public string Key {get; set;}
    public IEnumerable<string> Value {get; set;}
}

如果我有它的列表,正常序列化会产生以下输出:

[
    {
        "Key": "MyKey1",
        "Value": [
            "Value1",
            "Value2"
        ]
    },
    {
        "Key": "MyKey2",
        "Value": [
            "Value3",
            "Value4"
        ]
    }
]

我想要的是从 json-结果中删除 属性-名称,如下所示:

[    
    {
        "MyKey1": [
            "Value1",
            "Value2"
        ]
    },
    {
        "MyKey2": [
            "Value3",
            "Value4"
        ]
    }
]

所以我决定像这样实现自定义 JsonConverter:

public class MyClassJsonConverter : JsonConverter<MyClass>
{
    public override void Write(Utf8JsonWriter writer, MyClass value, JsonSerializerOptions options)
    {
        //custom code goes here
        writer.WriteStartArray(value.Key);

        foreach (var val in value.Value)
            writer.WriteStringValue(val);

        writer.WriteEndArray();
    }
}

但这会产生无效的json:

[
    "MyKey1": [
        "Value1",
        "Value2"
    ],
   "MyKey2": [
       "Value3",
       "Value4"
    ]
]

如何解决?

你应该在写入数组之前使用WriteStartObject(),在

之后使用WriteEndObject()
public override void Write(Utf8JsonWriter writer, MyClass value, JsonSerializerOptions options)
{
    writer.WriteStartObject();

    //custom code goes here
    writer.WriteStartArray(value.Key);

    foreach (var val in value.Value)
        writer.WriteStringValue(val);

    writer.WriteEndArray();
    writer.WriteEndObject();
}

然后是下面的代码

var list = new List<MyClass>
{
    new MyClass { Key = "MyKey1", Value = new[] { "Value1", "Value2" } },
    new MyClass { Key = "MyKey2", Value = new[] { "Value3", "Value4" } }
};

var options = new JsonSerializerOptions();
options.Converters.Add(new MyClassJsonConverter());
var json = JsonSerializer.Serialize(list, options);

给你预期的 JSON

[
    {
        "MyKey1": [
            "Value1",
            "Value2"
        ]
    },
    {
        "MyKey2": [
            "Value3",
            "Value4"
        ]
    }
]