我为此编写了一个源码分发版NuGet,它安装了带有两个自定义合同解析器的单个文件:
- PrivateSetterContractResolver
- PrivateSetterCamelCasePropertyNamesContractResolver
安装NuGet:
Install-Package JsonNet.PrivateSettersContractResolvers.Source
然后,只需使用任何解析器即可:
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
有两种替代方法可以解决此问题。
Alt 1:在反序列化器上
ContractResolver.DefaultMembersSearchFlags = DefaultMembersSearchFlags | BindingFlags.NonPublic;
默认的序列化选项支持所有类型的类成员。因此,此解决方案将返回所有私有成员类型,包括字段。我只对支持私人二传手感兴趣。
Alt2:创建一个自定义ContractResolver:
因此,这是更好的选择,因为我们只检查属性。
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/
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)