I want to locate my JsonSerializer settings in a separate file that forms a partial class along with the main class file. It is possible by using MetadataTypeAttribute
:
[MetadataType(typeof(MyMeta))]
public partial class MainClass
{
public int ID { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
internal sealed class MyMeta
{
[JsonIgnore]
public int ID { get; set; }
[JsonProperty(PropertyName = "Title")]
public string Name { get; set; }
[JsonProperty(PropertyName = "Functions")]
[JsonConverter(typeof(MyConverter))]
public string Description { get; set; }
}
But what if it is not possible to append MetadataTypeAttribute
to the MainClass
? I tried to use the derived class in my Web API controller instead:
public partial class MainClass
{
public int ID { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
[MetadataType(typeof(MyMeta))]
public partial class HelperClass : MainClass
{ }
public class TestController : ApiController
{
public IEnumerable<HelperClass> Get()
{
var list = new List<HelperClass>()
{
new HelperClass() { ID = 0, Name = "Title 0", Description = "Description 0"},
new HelperClass() { ID = 1, Name = "Title 1", Description = "Description 1"},
new HelperClass() { ID = 2, Name = "Title 2", Description = "Description 2"}
};
return list;
}
}
This trick works fine for validation attributes, but doesn't affect the TestController
result. Why?
What can I do to apply specific JsonSerializer settings to instances of MainClass
without overriding/shadowing/encapsulation its public properties?