Private setters in Json.Net(Json.Net 中的私人二传手)
问题描述
我知道有一个属性可以处理私有设置器,但我有点希望这种行为作为默认值,有没有办法做到这一点?除了调整源.如果有这个设置就好了.
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 中的私人二传手的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Json.Net 中的私人二传手
基础教程推荐
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- 将 XML 转换为通用列表 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- rabbitmq 的 REST API 2022-01-01