Reputation: 1437
I set up a WebApi Controller that is supposed to return a collection of objects which are of different type. Please have a short look at my dummy code:
interface IDish
{
int ID { get; set; }
string Name { get; set; }
}
class Steak : IDish
{
public int ID { get; set; }
public string Name { get; set; }
public string CookingStyle { get; set; }
public int Weight { get; set; }
}
class Soup : IDish
{
public int ID { get; set; }
public string Name { get; set; }
}
class Dessert : IDish
{
public int ID { get; set; }
public string Name { get; set; }
public bool ContainsSugar { get; set; }
}
public class DishController : ApiController
{
public IEnumerable<IDish> Get()
{
var dishes = busisnessLogic.GetDishes();
return dishes;
}
}
As you can see, in the controller I'm retrieving a collection of IDishes from my business logic. Please don't pay too much attention to the concrete classes. They are just samples to make the things easier to explain here. The real business background is totally different.
So, what's my problem? When the API controller returns the IDishes (in my case as Json), only the public properties of the IDish interface are written to the Json output.
Instead, I would like to have all the public properties of the concrete classes written to the Json output. So, for instance, if an IDish is a "Steak" I would like to have its ID, Name, CookingStyle and Weight written out. Accordingly just the ID and Name if it is a "Soup" and ID, Name and ContainsSugar if it is a "Dessert".
Is there an easy way to achieve this? Sometimes I tend to not see the trees before the woods...;-)
Thanks guys!
Upvotes: 1
Views: 538
Reputation: 4063
I needed pretty much the same functionality and I think there are 2 ways to go:
var jsonFormatter = config.Formatters.JsonFormatter;
var jsonSerializerSettings = new JsonSerializerSettings();
jsonFormatter.SerializerSettings.TypeNameHandling = TypeNameHandling.All;
Explanation: https://github.com/ayoung/Newtonsoft.Json/blob/master/Newtonsoft.Json/TypeNameHandling.cs
Basically, what you need to do is: - create a class derived from JsonCreationConverter in which you override the Create method to manually select the type of the object you want to create - the you update the settings:
var jsonSerializerSettings = new JsonSerializerSettings();
jsonSerializerSettings.Converters.Add(new YourCustomJsonConverter());
jsonFormatter.SerializerSettings = jsonSerializerSettings;
Check out this article, it describes it step by step: http://dotnetbyexample.blogspot.co.uk/2012/02/json-deserialization-with-jsonnet-class.html
Upvotes: 1