I need to deserialize a JSON string using Jackson into Lists of different Object types depending on the value set in one of the fields. I want to know what the best approach is for creating the different List Types and how i can implement this?
My JSON's would look something like this:
{"test":
{"conditions":[....],
"consequence": {"actionType":"string",
"action": ["value 1","value 2"]}
}
}
So when parsed the above would return a List<String>
{"test":
{"conditions":[....],
"consequence": {"actionType":"test",
"action": ["test","test"]}
}
}
and the above would return a List<Test>
My Pojo just contains:
@Data
public class Consequence {
public Consequence(String actionType){
this.actionType = actionType;
};
@JsonProperty("ACTIONTYPE")
private String actionType;
@JsonProperty("ACTION")
private List<????> action;
}
UPDATE:
After i updated my POJO's using the following hierarchy:
@Data
public abstract class BaseConsequence {
public BaseConsequence(String actionType){
this.actionType = actionType;
};
@JsonProperty("ACTIONTYPE")
private String actionType;
}
@Data
@DiscriminatorValue(value = "CONCATENATE")
public class ConcatenateConsequence extends BaseConsequence {
public ConcatenateConsequence(String actionType, List<String> concatenateValues) {
super(actionType);
this.concatenateValues = concatenateValues;
}
private List<String> concatenateValues;
}
@Data
@DiscriminatorValue(value = "test")
public class TestConsequence extends BaseConsequence {
public TestConsequence(String actionType, List<Test> tests){
super(actionType);
this.tests = tests;
}
private List<Test> tests;
}
@Data
public class Test {
public Test(){};
public Test(List<Condition> conditions, BaseConsequence baseConsequence){
this.conditions = conditions;
this.baseConsequence = baseConsequence;
}
@JsonProperty("CONDITIONS")
private List<Condition> conditions;
@JsonProperty("CONSEQUENCE")
private BaseConsequence baseConsequence;
@Override
public boolean equals(Object o) {
if (o == this) return true;
if (!(o instanceof Test)) {
return false;
}
Test test = (Test) o;
return Objects.equals(conditions, test.conditions) && Objects.equals(baseConsequence, test.baseConsequence);
}
@Override
public int hashCode() {
return Objects.hash(conditions, baseConsequence);
}
}
I get the following error:
com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.util.ArrayList out of START_OBJECT token
at [Source: {"TEST":{"CONDITIONS":[{"KEY":"KEY1","VALUES":["FLOAT"],"OPERATOR":""}],"CONSEQUENCE":{"ACTIONTYPE" :{"CONCATENATE": ["VALUE1","VALUE2"]}}}}; line: 1, column: 9] (through reference chain: package.TestCase["TEST"])
There are two variants you can use:
@DiscriminatorValue
. See here for full description and examples http://www.baeldung.com/jackson-inheritance
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.