For my ASP.NET MVC webservice I have a model that I return as a JSON object. Now there are some properties in my model that I don't want to return.
An example model:
class Account {
public int ID { get; }
public string Username { get; }
public string Password { get; }
//... more properties
}
Let's say I only want to return the ID and Username properties as JSON. I am looking for a good way to filter only these properties. Changing the access modifier is not an option for me.
A solution which I could think of is creating a whitelist like below. Here I have added a DisplayName which would be a nice thing to be able to customize, but it isn't required.
class FilterProperty
{
public string PropertyName { get; }
public string DisplayName { get; }
public FilterProperty(string propertyName, string displayName)
{
PropertyName = propertyName;
DisplayName = displayName;
}
}
class Account
{
public static FilterProperty[] Whitelist = {
new FilterProperty("ID", "accountId"),
new FilterProperty("Username", "accountName")
};
//...
}
The downside to this solution is: if I would change the name of a property, I would need to change the whitelist too.
Could I make this work or are there better solutions?