通过阅读有关.NET 8序列化的公告和文档,我的印象是我们可以序列化到私有字段中.
我试着做以下几件事:
public class User
{
[JsonInclude]
[JsonPropertyName("name")]
private string _name = null!;
public int Age { get; }
[JsonConstructor]
private User(string name, int age)
{
_name = name;
Age = age;
}
private User(){}
}
...
var userStr = @"{""name"": ""juan"", ""age"": 31}";
var options = new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true,
IncludeFields = true,
IgnoreReadOnlyFields = false
};
var user = JsonSerializer.Deserialize<User>(userStr, options)!;
这就抛出了
Unhandled exception. System.InvalidOperationException: Each parameter in the deserialization constructor on type 'User' 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.
at System.Text.Json.ThrowHelper.ThrowInvalidOperationException_ConstructorParameterIncompleteBinding(Type parentType)...
将私有字段更改为公开如下获取方法的属性
public string Name { get; }
可以,但问题是我希望它是一个私有领域.在我的实际场景中,我有一个private List<T>
,但我只公开了一个public IReadOnlyCollection<T>
,它的getter将列表返回为只读.
有没有办法告诉序列化使用私有字段?