I have an issue in converting JSONArray into a List using Jackson Object Mapper.
public class Main {
public static void main(String[] args) throws Exception {
String test = Files.readString(Path.of("test.json"));
callRequired(test);
}
public static void callRequired(String test) {
ObjectMapper mapper = new ObjectMapper();
try {
List<Condition> result = mapper.readerForListOf(Condition.class).readValue(test.trim());
System.out.println(result);
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
}
The test.json is:
{
"condition": [
{
"type": "NONE",
"subConditons": [
{
"type": "NONE",
"subConditions": []
},
{
"type": "AND",
"subConditions": [
{
"type": "NONE",
"subConditions": []
}
]
}
]
},
{
"type": "OR",
"subConditions": []
}
]
}
The Condition class is as follows:
public class Condition {
Type type = Type.NONE;
List<Condition> subConditions;
public Condition() {
}
public Condition(Type type, List<Condition> subConditions) {
this.type = type;
this.subConditions = subConditions;
}
public List<Condition> getSubConditions() {
return subConditions;
}
public void setSubConditions(List<Condition> subConditions) {
this.subConditions = subConditions;
}
public Type getType() {
return type;
}
public void setType(Type type) {
this.type = type;
}
public enum Type {
NONE,
AND,
OR;
}
@Override
public String toString() {
return "Condition [type=" + type + ", subConditions=" + subConditions + "]";
}
}
Edit: The Condition array contains a list of conditions within which lies a subCondition which is also a type of Condition.
EDIT: Thanks, I have added the requisite braces and checked for its validity. I have also added an all args construcutor and a no args constructor as well.
How do I change the JSON so that I receive a List of conditions with the proper subconditions nested with Jackson.
2
Answers
In your JSON, the "condition" object starts with a "[", setting its type to an array. This isn’t how your condition object class look like.
It should be more like:
If you have no objection to switching to Gson, here is a basic parse.
Output