在构造函数参数的类型与具有匹配名称的属性的类型不匹配的情况下,使STJ正确反序列化的最佳方法是什么?
请考虑以下代码示例:
using System.Text.Json;
string data = """
{
"Ints": [24, 43, 54, 23]
}
""";
var parsed = JsonSerializer.Deserialize<Data>(data)!;
class Data
{
public Data(IEnumerable<int> ints)
{
Ints = ints.ToList().AsReadOnly();
}
public IReadOnlyCollection<int> Ints { get; }
}
构造函数参数ints
的类型与属性Ints
的类型不匹配.这会导致反序列化失败,尽管这个用例看起来非常合理.
反序列化在Newtonsoft上的工作与预期一样,但如果可能的话,我想使用STJ.
例外消息:
System.InvalidOperationException:
Each parameter in the deserialization constructor on type 'Data' 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.