I am having trouble in deserialising the below JSON String to a Java Object.
{ "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 –
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
public class Alert{ @JsonProperty("isEnabled") public boolean isEnabled; @JsonProperty("name") public String name; }
AlertConfig.java
public class AlertConfig { @JsonProperty("onSuccess") public Alert onSuccess; @JsonProperty("onWarning") public Alert onWarning; @JsonProperty("onError") public Alert onError; }
JobConfig.java
public class JobConfig { @JsonProperty("action") public AlertConfig action; }
Error i get is :
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 –
public class AlertWrapper { @JsonProperty("alert") public Alert alert; }
And your AlertConfig class should contain AlertWrapper like below –
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)