问题描述
我知道有一个属性可以处理私有设置器,但我有点希望这种行为作为默认值,有没有办法做到这一点?除了调整源.如果有这个设置就好了.
I know there's an attribute to handle private setters but I kind of want this behavior as a default, is there a way to accomplish this? Except tweaking the source. Would be great if there was a setting for this.
推荐答案
更新,新答案
我为此编写了一个源代码分发 NuGet,它安装了一个带有两个自定义合同解析器的文件:
Updated, new answer
I've written a source distribution NuGet for this, that installs a single file with two custom contract resolvers:
- PrivateSetterContractResolver
- PrivateSetterCamelCasePropertyNamesContractResolver
安装 NuGet 包:
Install-Package JsonNet.ContractResolvers
然后只需使用任何解析器:
Then just use any of the resolvers:
var settings = new JsonSerializerSettings
{
ContractResolver = new PrivateSetterContractResolver()
};
var model = JsonConvert.DeserializeObject<Model>(json, settings);
你可以在这里阅读:http://danielwertheim.se/json-net-private-setters-nuget/
GitHub 存储库:https://github.com/danielwertheim/jsonnet-privatesetterscontractresolvers
GitHub repo: https://github.com/danielwertheim/jsonnet-privatesetterscontractresolvers
有两种方法可以解决问题.
There are two alternatives that can solve the problem.
Alt 1:在反序列化器上
ContractResolver.DefaultMembersSearchFlags =
DefaultMembersSearchFlags | BindingFlags.NonPublic;
默认的序列化选项支持所有类型的类成员.因此,此解决方案将返回所有私有成员类型,包括字段.我只对支持私人二传手感兴趣.
The default serialization option supports all types of class member. Therefore this solution will return all private members types including fields. I'm only interested in also supporting private setters.
Alt2:创建自定义 ContractResolver:
因此这是更好的选择,因为我们只检查属性.
Therefore this is the better options since we just check the properties.
public class SisoJsonDefaultContractResolver : DefaultContractResolver
{
protected override JsonProperty CreateProperty(
MemberInfo member,
MemberSerialization memberSerialization)
{
//TODO: Maybe cache
var prop = base.CreateProperty(member, memberSerialization);
if (!prop.Writable)
{
var property = member as PropertyInfo;
if (property != null)
{
var hasPrivateSetter = property.GetSetMethod(true) != null;
prop.Writable = hasPrivateSetter;
}
}
return prop;
}
}
有关更多信息,请阅读我的帖子:http://danielwertheim.se/json-net-private-setters/
For more information, read my post: http://danielwertheim.se/json-net-private-setters/
这篇关于Json.Net 中的私人二传手的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!