【发布时间】:2020-08-07 10:25:13
【问题描述】:
我希望将 [JsonProperty("name")] 和 ![JsonIgnore] 组合到我自己的自定义解析器中,我只需要一些语法方面的帮助。
所以当序列化这个类时,我想忽略所有没有我的自定义属性的属性,并像这样指定属性的序列化名称:
public class MyClass
{
[MyCustomProperty("name")]
public string SomeName { get; set; }
[MyCustomProperty("value")]
public string SomeValue { get; set; }
public string AnotherName {get; set; }
public string AnotherValue {get; set; }
}
预期结果:
{
"name": "Apple",
"value": "Delicious"
}
这是我使用解析器所取得的进展:
public class MyCustomProperty : Attribute
{
public string Property { get; set; }
public MyCustomProperty(string property)
{
Property = property;
}
}
public class CustomResolver : DefaultContractResolver
{
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
JsonProperty property = base.CreateProperty(member, memberSerialization);
Type itemType = property.PropertyType.GetGenericArguments().First();
MyCustomProperty customProperty = itemType.GetCustomAttribute<MyCustomProperty>();
property.PropertyName = MyCustomProperty.Property;
return property;
}
}
我不确定在哪里添加 ignore if no attribute 部分。
【问题讨论】:
标签: c# json.net json-serialization