I didn't find any topics on the same problem. Correct me if I am wrong.
The following JSON is the simplified version of the response I get back from an external API:
{
"vehicles": [
{
"car": {
"color": "blue",
"brand": "audi",
"maxSpeed": 300,
"releaseYear": 2016
}
},
{
"car": {
"color": "red",
"brand": "bmw",
"maxSpeed": 200,
"releaseYear": 2012
}
},
{
"motorcycle": {
"color": "yellow",
"brand": "yamaha",
"maxSpeed": 300,
"releaseYear": 2013
}
}
]
}
So I get a list of vehicles and each element is an object that has one field named either car or motorcycle, no other options are possible. Both types of vehicles have exactly the same data fields . The only way to differentiate both types is by the name of the key in JSON
How I want to parse it:
In Java I have three objects:
abstract class Vehicle {
String color;
String brand;
Integer maxSpeed;
Integer releaseYear
public boolean hasFourWheels();
}
class Car extends Vehicle {
public boolean hasFourWheels() { return true; }
}
class Motorcycle extends Vehicle {
public boolean hasFourWheels() { return false; }
}
Is it possible to get a list of Vehicles where each instance is either Car or Motorcycle?