如何编写System.Text.Json转换器解决三层嵌套字典反序列化报错问题
解决System.Text.Json反序列化三层嵌套字典到StringCollection的问题
你遇到的错误是因为System.Text.Json没有内置对StringCollection类型的序列化/反序列化支持,当它尝试把JSON数组转成StringCollection时,无法自动将JsonElement转换为string,导致类型转换失败。
我们可以编写一个自定义的JsonConverter<StringCollection>来处理StringCollection和JSON数组之间的转换,这样整个三层嵌套字典的反序列化就能正常工作。
自定义转换器代码
using System.Collections.Specialized; using System.Text.Json; using System.Text.Json.Serialization; public class StringCollectionConverter : JsonConverter<StringCollection> { public override StringCollection Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { // 检查当前JSON token是否为数组类型 if (reader.TokenType != JsonTokenType.StartArray) { throw new JsonException("Expected JSON array for StringCollection"); } var stringCollection = new StringCollection(); // 遍历数组中的每个元素 while (reader.Read()) { if (reader.TokenType == JsonTokenType.EndArray) { break; } // 将JsonElement转换为string并添加到StringCollection if (reader.TokenType == JsonTokenType.String) { stringCollection.Add(reader.GetString()); } else { // 遇到非字符串元素时抛出异常,可根据需求调整处理逻辑 throw new JsonException("Expected string element in JSON array"); } } return stringCollection; } public override void Write(Utf8JsonWriter writer, StringCollection value, JsonSerializerOptions options) { // 序列化时将StringCollection转为JSON数组 writer.WriteStartArray(); foreach (string item in value) { writer.WriteStringValue(item); } writer.WriteEndArray(); } }
转换器的使用方式
方式1:全局配置(推荐)
在JsonSerializerOptions中添加转换器,所有StringCollection类型都会自动使用该转换器处理:
var options = new JsonSerializerOptions(); options.Converters.Add(new StringCollectionConverter()); // 反序列化示例 string json = @"{""ACL"": {""granted"": {""Business"": {""Delete"": [""Customer1"",""Customer2""]},""Account"": {""Create"": [""Customer1"",""Customer3""]}}}}"; var aclRecord = JsonSerializer.Deserialize<AclRecord>(json, options);
方式2:属性级配置
如果后续有单独的StringCollection属性,可以直接在属性上标记使用该转换器:
public record SomeRecord { [JsonConverter(typeof(StringCollectionConverter))] public StringCollection Items { get; set; } }
使用上述代码后,就能成功将给定的JSON反序列化为你定义的AclRecord类型,三层嵌套字典中的StringCollection会正确填充对应的值。
内容的提问来源于stack exchange,提问作者Charles
相关产品推荐
相关产品推荐

