c# - 如何使用 System.Text.Json 正确反序列化具有 IReadOnlyCollection<T> 的类?

标签 c# json json-deserialization system.text.json readonly-collection

我有以下类(class):

public sealed class SomeClass
{
    [JsonConstructor()]
    public SomeClass(IEnumerable<string> myItems)
    {
        InternalMyItems = new Collection<string>(myItems.ToArray());
        MyItems = new ReadOnlyCollection<string>(InternalMyItems);
    }
    
    public IReadOnlyCollection<string> MyItems { get; }
    private Collection<string> InternalMyItems { get; }
}

序列化似乎工作正常:

{
  "MyItems": [
    "A",
    "B",
    "C"
  ]
}

反序列化似乎不起作用。理想情况下,我想坚持使用 ReadOnlyCollection<T>Collection<T>而不必更改为其他一些类型。此示例代码在尝试反序列化时引发异常:

var options = new JsonSerializerOptions()
{
    WriteIndented = true
};

var items = new[] { "A", "B", "C" };
var instance = new SomeClass(items);

var json = JsonSerializer.Serialize(instance, options);

var copy = JsonSerializer.Deserialize<SomeClass>(json, options);

InvalidOperationException: Each parameter in the deserialization constructor on type 'UserQuery+SomeClass' must bind to an object property or field on deserialization. Each parameter name must match with a property or field on the object. Fields are only considered when 'JsonSerializerOptions.IncludeFields' is enabled. The match can be case-insensitive.


以下是代码运行并给出错误的 .NET Fiddle 示例:https://dotnetfiddle.net/vorOLX

最佳答案

构造函数参数的类型和名称必须与类中的属性匹配。 System.Text.Json 还知道如何构造 IReadOnlyCollection<T>直接使用,所以只需使用该类型。例如,您可以简单地执行以下操作:

public sealed class SomeClass
{
    [JsonConstructor]
    public SomeClass(IReadOnlyCollection<string> myItems)
                   // ^^^^ matching type         
    {
        MyItems = myItems;
    }

    public IReadOnlyCollection<string> MyItems { get; }
}

关于c# - 如何使用 System.Text.Json 正确反序列化具有 IReadOnlyCollection<T> 的类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75988393/

相关文章:

java - Gson如何将json转换为自定义类

c# - 我需要一个慢速 C# 函数

c# - 了解 float 问题

c# - 将大括号与单行 "if"语句的语句放在同一行是否是一种错误的形式?

javascript - 使用 vanilla javascript 将 .json 数据添加到表中

symfony - 在 symfony2 中创建 JMS Serializer 处理程序

c# - 来自基本接口(interface)的通用类型

json - 读取JSON文件并将其保存在SAS数据集中

python - 从 YouTube API 响应中选择特定键

java - 使用继承的自定义 JsonDeserializer 导致 StackOverflowError