Specify class type in JSON response

I created a basic capapap C # application that returns JSON.

There will be several classes in my system, as an example I will use cars.

I have an abstract class called Car, which has many different types of cars that are inherited from Car. Examples are a truck, sedan, limo, bulldozer, ambulance, etc. All of them have some additional properties.

Everything in my application works as expected, but when I request / api / Cars / and return all the cars, I can 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 a person consuming this, how do they know that the first element is an SUV, the second is a bulldozer, and the third is an ambulance?

Am I adding a property to a base class called "CarType" that they will use conditionally to map it to the class at the end?

+6
source share
1 answer

You can use the DTO template to combine all the properties that you want to open from the web API to the client.

In your case, this can be done: 1- Create a CarDto class (you can use the name anohter if you want) with all the properties you want to open 2 - Create a list of CarDto types that will be filled with your data 3 - Replace your cars with the result with cars . Result.

Hope this helps you.

+1
source

Source: https://habr.com/ru/post/988336/


All Articles