I am new to deserialization and I am trying to deserialize the complex JSON for my class. I am using Jackson 2.12.1
. I wanted to know how to map the following JSON structure to my class when there are multiple cases that map to the different root element
I have a JSON file in my Resources folder of the classpath and its something like this:
{
"Employee":{
"firstName":"First Name",
"lastName":"Last Name",
"department":"Department"
},
"Student":{
"firstName":"Student First Name",
"lastName":"Student Last Name",
"studentID":"1234"
}
}
I have 2 class for Employee
and Car
separately which extends the Person
abstract class and its something like this:
@Getter
@Setter
public abstract class person{
private String firstName;
private String lastName;
}
@Getter
@Setter
@JsonRootName(value = "Employee")
public Employee extends person{
private String department;
}
@Getter
@Setter
@JsonRootName(value = "Student")
public Student extends person{
private String studentID;
}
public class MainClass{
public static void main(String []args){
String jsonFile = FileUtils.readFileToString(new File("src/main/resources/myFile.json"), "UTF-8");
final ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
Employee eventInfo = objectMapper.readValue(jsonFile, Employee.class);
//This works for Employee but I want to make sure that it works for Student as well based on the ROOT ELEMENT value within the JSON
}
}
This works for Employee
but how can I configure it to work for all the type based on the different ROOT ELEMENT values within the JSON? I feel I am missing some basic thing can someone please help me?
PS: I am using the @Getter and @Setter from the Project Lombok