So I have JSON that looks like this:
{
\"ActivityDisplayModel\" : {
\"name\" : \"lunch with friends\",
\"startTime\" : \"12:00:00\",
I am not sure that you can do it with specifying inner property: type.id
. In my opinion you should change your JSON to simpler version. If you can not force your JSON supplier to change JSON schema you have to do it manually. Assume that your JSON looks like below:
{
"activityDisplayModel": {
"name": "lunch with friends",
"type": {
"id": "MEAL",
"description": "Meal"
},
"complete": false
}
}
Below POJO classes fit to above JSON:
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type")
@JsonSubTypes({
@JsonSubTypes.Type(value = MealDisplayModel.class, name = "MEAL"),
@JsonSubTypes.Type(value = EntertainmentDisplayModel.class, name = "ENTERTAINMENT")
})
abstract class ActivityDisplayModel {
protected String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return name;
}
}
class MealDisplayModel extends ActivityDisplayModel {
private boolean complete;
public boolean isComplete() {
return complete;
}
public void setComplete(boolean complete) {
this.complete = complete;
}
@Override
public String toString() {
return "MealDisplayModel [complete=" + complete + ", toString()=" + super.toString() + "]";
}
}
@JsonIgnoreProperties("complete")
class EntertainmentDisplayModel extends ActivityDisplayModel {
@Override
public String toString() {
return "EntertainmentDisplayModel [toString()=" + super.toString() + "]";
}
}
class Root {
private ActivityDisplayModel activityDisplayModel;
public ActivityDisplayModel getActivityDisplayModel() {
return activityDisplayModel;
}
public void setActivityDisplayModel(ActivityDisplayModel activityDisplayModel) {
this.activityDisplayModel = activityDisplayModel;
}
@Override
public String toString() {
return activityDisplayModel.toString();
}
}
Below script shows how you can parse above JSON:
ObjectMapper mapper = new ObjectMapper();
// Updated JSON in memory
ObjectNode rootNode = (ObjectNode)mapper.readTree(json);
ObjectNode activityDisplayModelNode = (ObjectNode)rootNode.path("activityDisplayModel");
JsonNode typeNode = activityDisplayModelNode.path("type");
activityDisplayModelNode.set("type", typeNode.path("id"));
System.out.println("Result: " + mapper.convertValue(rootNode, Root.class));
Above script prints:
Result: MealDisplayModel [complete=false, toString()=lunch with friends]
Also see: