Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specify Class Type in JSON Response

I have built a basic c# webapi application that returns JSON.

My system will have a number of classes, I will use cars as an example.

I have an abstract class called Car that has many different types of cars that inherit from the Car. Examples would be Truck, Sedan, Limo, Bulldozer, Ambulance, etc. These all have some additional properties.

Everything in my app is working as expected, but when I query /api/Cars/ and get back all cars, I might get something like this:

{
    "Id": 6290,
    "Make": "GM",
    "Model": "Yukon",
    "Seats": 7
},
{
    "Id": 6291,
    "Make": "Caterpillar",
    "Model": "D11T",
    "BucketWidth": 14.5
},
{
    "Id": 6292,
    "Make": "Braun",
    "Model": "Express",
    "Siren": "ACME"
}

So, as the person consuming this, how do they know that the first item is an SUV, the second is a Bulldozer, and the 3rd an ambulance?

Do I add a property to the base class called "CarType" that they would use conditionally to map it to a class on their end?

like image 990
enforge Avatar asked Jun 01 '15 18:06

enforge


1 Answers

You can use the DTO Pattern to merge all the properties that you want to expose from web API to the client.

  • Dto pattern definition
  • Dto example

In your case can do this: 1- Create a CarDto class (you can use anohter name if you prefer) with all the properties that you want to expose 2 - Create a List of type CarDto which will be filled with your data 3 - Replace your cars result with the cars dto result.

I hope this will helps you.

like image 61
Fermín Avatar answered Nov 13 '22 00:11

Fermín