使用带有Json.Net的Custom Contract Resolver反序列化对象时的NamingStrategy

时间:2019-11-22 07:25:07

标签: json.net deserialization

我正在与JsonProperty一起使用自定义合同解析器。

这是我的课程

public class Foo {
  [JsonProperty('id')]
  public int Id { get; set; }
  [JsonProperty('fullname')]
  public int FullName { get; set; }
}

并有一个自定义合同解析器

    public class CustomContractResolver : DefaultContractResolver
    {
        public bool UsePropertyName { get; }

        public CustomContractResolver(bool useJsonPropertyName)
        {
            NamingStrategy = new CamelCaseNamingStrategy(true, true);
            UsePropertyName = useJsonPropertyName;
        }

        protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
        {
            var property = base.CreateProperty(member, memberSerialization);
            if (!UsePropertyName)
                property.PropertyName = property.UnderlyingName;

            return property;
        }
    }

但是当我反序列化json时,此自定义合同解析器将不应用命名策略。

请注意,此合同解析器在dotnet核心应用程序的Startup类中初始化,并且在反序列化时不作为参数传递。

感谢所有帮助:)

0 个答案:

没有答案