因此,使用访问器设置可枚举的操作非常有效。
public class SetEnumerableWithAccessor
{
public IEnumerable<string>? Strings { get; set; }
}
string json = JsonSerializer.Serialize(new SetEnumerableWithAccessor
{
Strings = new [] { "test" }
});
JsonSerializer.Deserialize<SetEnumerableWithAccessor>(json);
设置可枚举的使用构造函数失败。
public class SetEnumerableWithConstructor
{
[JsonConstructor]
public SetEnumerableWithConstructor(IEnumerable<string> strings)
{
Strings = strings.ToImmutableList();
}
public ImmutableList<string> Strings { get; }
}
string json = JsonSerializer.Serialize(new SetEnumerableWithConstructor(new string[] { "test" }));
JsonSerializer.Deserialize<SetEnumerableWithConstructor>(json);
这是抛出的异常。
System.InvalidOperationException
Each parameter in the deserialization constructor on type 'CertusLogic.Audio.Test.FourierTransformTest+SetEnumerableWithConstructor' must bind to an object property or field on deserialization. Each parameter name must match with a property or field on the object. The match can be case-insensitive.
at System.Text.Json.ThrowHelper.ThrowInvalidOperationException_ConstructorParameterIncompleteBinding(Type parentType)
at System.Text.Json.Serialization.Converters.ObjectWithParameterizedConstructorConverter`1.OnTryRead(Utf8JsonReader& reader, Type typeToConvert, JsonSerializerOptions options, ReadStack& state, T& value)
at System.Text.Json.Serialization.JsonConverter`1.TryRead(Utf8JsonReader& reader, Type typeToConvert, JsonSerializerOptions options, ReadStack& state, T& value)
at System.Text.Json.Serialization.JsonConverter`1.ReadCore(Utf8JsonReader& reader, JsonSerializerOptions options, ReadStack& state)
at System.Text.Json.JsonSerializer.ReadFromSpan[TValue](ReadOnlySpan`1 utf8Json, JsonTypeInfo jsonTypeInfo, Nullable`1 actualByteCount)
at System.Text.Json.JsonSerializer.ReadFromSpan[TValue](ReadOnlySpan`1 json, JsonTypeInfo jsonTypeInfo)
at System.Text.Json.JsonSerializer.Deserialize[TValue](String json, JsonSerializerOptions options)
把我的头撞在一个应该很简单的东西上。
发布于 2022-05-17 11:27:45
当使用参数化构造函数反序列化类时,Sytem.Text.Json要求构造函数参数与序列化属性匹配。来自文档
参数化构造函数的参数名称必须与属性名称匹配。匹配不区分大小写,即使使用
[JsonPropertyName]
重命名属性,构造函数参数也必须与实际的属性名称匹配。
文档中没有说明的是,构造函数参数和相应属性的类型也必须与完全匹配。如需确认,请参阅。
因此,必须使用ImmutableList<string> strings
参数将构造函数添加到类中,并使用[JsonConstructor]
标记该构造函数,并且只标记该构造函数。
public class SetEnumerableWithConstructor
{
[JsonConstructor]
public SetEnumerableWithConstructor(ImmutableList<string> strings) => Strings = strings;
public SetEnumerableWithConstructor(IEnumerable<string> strings) => Strings = strings.ToImmutableList();
public ImmutableList<string> Strings { get; }
}
现在您的类将是可序列化的。这里演示小提琴:https://dotnetfiddle.net/wo5TlF。
https://stackoverflow.com/questions/72268018
复制相似问题