I have to map a JSON to Java PoJos using JAX-RS (Resteasy as implementation). The problem is, that the JSON is dynamic. Look at this example:
{
"typeCode": "SAMPLE",
"data": [
{
"id": "COMMENTS",
"answerValue": {
"type": "YesNoAnswer",
"value": true
}
},
{
"id": "CHOICE",
"answerValue": {
"type": "SelectListAnswer",
"values": ["choice1", "choice2"]
}
}
]
}
The dynamic elements are in the data array. In principal every entry has an ID and an answerValue. But the answerValue is dynamic. Depending on his type he can have a single value (boolean, string, number an object) or an array of values.
How can I map this to my Java model?
Thanks to the @Henrik of his solution. While implementing his proposal, I found a different solution, which suites better for me. I just use JsonSubTypes Annotation to handle inheritance. This is my example:
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
@JsonTypeInfo(
use = JsonTypeInfo.Id.NAME,
include = JsonTypeInfo.As.PROPERTY,
property = "type")
@JsonSubTypes({
@JsonSubTypes.Type(value = YesNoAnswer.class, name = "YesNoAnswer"),
@JsonSubTypes.Type(value = SelectListAnswer.class, name="SelectListAnswer"),
@JsonSubTypes.Type(value = SelectAddressAnswer.class, name="SelectAddressAnswer")})
abstract class RequestFormAnswer {
private String type;
}