Reputation: 420
I have a Spring boot application where I am using RestTemplate to call a Rest API and I receive following JSON formatted response:
{
"data": [
{
"id": "1",
"type": "type1",
"config": {
"property1" : "value1",
"property2" : "value2"
}
},
{
"id": "2",
"type": "type2",
"config": {
"property3" : "value3",
"property4" : "value4",
"propArray": [ "element1", "element2"]
}
}
]
}
The individual elements within array 'data' has few different structures (2 examples above) where I would like to map different Class Types with individual elements which depends on the value of the element 'type'.
For example value 'type1' should map to an object of Class type 'Type1' and so on.
I have Classes created as below: MyResponse:
public Class MyResponse {
List<Data> data;
..
\\getter and setters
}
Data:
public Interface Data {}
Type1:
public Class Type1 implements Data {
private String property1;
private String property2;
..
\\getter and setters
}
Type2:
public Class Type1 implements Data {
private String property3;
private String property4;
private List<String> propArray;
..
\\getter and setters
}
How can I map above conditional structure?
Upvotes: 1
Views: 2669
Reputation: 26947
Only way I could think of it is get the returned value a String, convert it to JSONObject and process it to create your instances of your classes. For example,
String response = restTemplate.<your-uri>
JSONObject jsonObject = new JSONObject(response);
if (jsonObject.get(type).equals(type1) {
Type1 type1 = new Type1();
// set values
} else if (jsonObject.get(type).equals(type2) {
Type2 type2 = new Type2()
// set values
}
However, this is not scalable and if you are going add more and more types it would be very difficult to maintain a clean code.
Another way you can do this is to create a General Class and receive the response as List of that class. In this way Spring-boot/ jackson cand do the mapping. Again you have to add code to create the other classes from this general class. As Sam pointed out in the comment, this would be a preferred one since Jackson is faster than JSONObject. Here is sample class would look like,
class Response {
private Integer id;
private String type;
private Map<String, Object> config;
}
You still have to check the type and map to corresponding class.
Instead of writing such messy code, I would consider if I could re-architect your design/ response sent if you have control over it.
Upvotes: 2