I am having trouble in deserialising the below JSON String to a Java Object.
JavaScript
x
{
"action": {
"onWarning":{
"alert":{
"isEnabled": true,
"name": ""
}
},
"onError":{
"alert":{
"isEnabled": true,
"name": ""
}
},
"onSuccess":{
"alert":{
"isEnabled": true,
"name": ""
}
}
}
}
The code below should work but i think my issue is with the mapper i am passing with it –
JavaScript
ObjectMapper mapper = new ObjectMapper();
JobConfig lib = mapper.readValue(jsonString, JobConfig.class);
System.out.println(lib.action.onWarning.alert.isEnabled);
The mapper i pass with it is like below :
Alert.java
JavaScript
public class Alert{
@JsonProperty("isEnabled")
public boolean isEnabled;
@JsonProperty("name")
public String name;
}
AlertConfig.java
JavaScript
public class AlertConfig {
@JsonProperty("onSuccess")
public Alert onSuccess;
@JsonProperty("onWarning")
public Alert onWarning;
@JsonProperty("onError")
public Alert onError;
}
JobConfig.java
JavaScript
public class JobConfig {
@JsonProperty("action")
public AlertConfig action;
}
Error i get is :
JavaScript
com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "alert" (class com.test.dv.service.domain.Alert), not marked as ignorable (2 known properties: "name", "isEnabled"])
I am nor sure how to name the content of alert JSON as alert but it already has been named as Alert.
Advertisement
Answer
You should create an AlertWrapper Class like below –
JavaScript
public class AlertWrapper {
@JsonProperty("alert")
public Alert alert;
}
And your AlertConfig class should contain AlertWrapper like below –
JavaScript
public class AlertConfig {
@JsonProperty("onSuccess")
public AlertWrapper onSuccess;
@JsonProperty("onWarning")
public AlertWrapper onWarning;
@JsonProperty("onError")
public AlertWrapper onError;
}
Doing this you will complete your DTO(s)