我有以下类(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/