1

I have a class Car, whose properties are String tyre, and Engine engine. and Engine is an abstract class that is been extended by Class Electric and Class Mechanical. Class Electric has property String battery, and Class Mechanical has property String piston.

Code for each class are:

class Car:

package com.kri.demo;

public class Car {
    String tyre;
    Engine engine; //abstract class
    //getters and setters...
}

Class Engine:

package com.kri.demo;

public abstract class Engine {

    String brand;
    //getters and setters
}

Class Mechanical :

package com.kri.demo;

public class Mechanical extends Engine{

    String pistonSize;
}

Class Electric:

package com.kri.demo;

public class Electric extends Engine{

    String batteryCap;
}

I want to use class car in @RequestBody, I need to make a json request to post a information about Car. How can I make a json request for the inherited class Electric or Mechanical within json object Car?

"car":{
   "tyre" : "goodDear",
   "engine": ???
}
devlover
  • 41
  • 3
  • 6
  • 1
    Please show your actual code to go along with the English description. – Code-Apprentice Nov 22 '19 at 20:25
  • I suggest you use a library like GSON that serializes your Java classes directly to JSON for you. – Code-Apprentice Nov 22 '19 at 20:26
  • https://www.baeldung.com/jackson-inheritance, https://github.com/FasterXML/jackson-docs/wiki/JacksonPolymorphicDeserialization. These are 2 relevant links you find when googling for "Jackson inheritance". – JB Nizet Nov 22 '19 at 20:53
  • You can `activateDefaultTyping` and provide class of an engine, see [Which version of jackson-databind does not have remote execution vulnerability?](https://stackoverflow.com/questions/58754487/which-version-of-jackson-databind-does-not-have-remote-execution-vulnerability) or use [JacksonPolymorphicDeserialization](https://github.com/FasterXML/jackson-docs/wiki/JacksonPolymorphicDeserialization). Some examples: [Polymorphic deserialization of property](https://stackoverflow.com/questions/59000068/jackson-polymorphic-deserialization-of-property-using-an-existing-sibling-proper) – Michał Ziober Nov 22 '19 at 23:14
  • [Jackson JsonTypeInfo.As.EXTERNAL_PROPERTY doesn't work as expected](https://stackoverflow.com/questions/18757431/jackson-jsontypeinfo-as-external-property-doesnt-work-as-expected), [Polymorphic JSON deserialization of an object with an interface property?](https://stackoverflow.com/questions/21485923/java-jackson-polymorphic-json-deserialization-of-an-object-with-an-interface-pr), [Java unmarshilling JSON data containg abstract type](https://stackoverflow.com/questions/16800896/java-unmarshilling-json-data-containg-abstract-type) – Michał Ziober Nov 22 '19 at 23:16

0 Answers0