I'm looking to combine [JsonProperty("name")]
and ![JsonIgnore]
into my own custom resolver and I just need some help on the syntax.
So when serializing this class I want to ignore all properties without my custom attribute and also specify the serialized name for the property like so:
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; }
}
Expected result:
{
"name": "Apple",
"value": "Delicious"
}
This is how far I got with my resolver:
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;
}
}
I'm not exactly sure where to add the ignore if no attribute part.