下面是示例JSON字符串。我想解析这个嵌套的JSON对象,即使嵌套对象有相同的名称。有时我们可能会有多个层次的嵌套对象。我厌倦了Jackson嵌套对象解析,但这对我不起作用。解析完对象后,我想把它转换成不同的格式。请帮助我解析这个JSON。先谢了。
{
"operator": "and",
"predicates": [
{
"operator": "and",
"predicates": [
{
"columnName": "userName",
"datatype": "string",
"input": "text",
"operand": "equal",
"value": "xxxx"
},
{
"columnName": "Age",
"datatype": "number",
"input": "number",
"operand": "greater_or_equal",
"value": "21"
}
]
},
{
"operator": "and",
"predicates": [
{
"columnName": "userName",
"datatype": "string",
"input": "text",
"operand": "not_equal",
"value": "nnn"
},
{
"columnName": "Birthday",
"datatype": "date",
"input": "date_picker",
"operand": "in",
"value": "2020-07-23,2020-07-24"
}
]
}
]
}
下面是java中的代码
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonProperty;
public class Predicates {
private String columnName;
private String datatype;
private String input;
private String operator;
private String value;
private String operand;
/**
*
*/
private List<Predicates> predicates;
@JsonProperty("predicates")
private void unpackNested(Map<String,Object> predicates) {
this.columnName = (String)predicates.get("columnName");
this.datatype = (String)predicates.get("datatype");
this.input = (String)predicates.get("input");
this.operator = (String)predicates.get("operator");
this.value = (String)predicates.get("value");
this.operand = (String)predicates.get("operand");
}
public String getColumnName() {
return columnName;
}
public void setColumnName(String columnName) {
this.columnName = columnName;
}
public String getDatatype() {
return datatype;
}
public void setDatatype(String datatype) {
this.datatype = datatype;
}
public String getInput() {
return input;
}
public void setInput(String input) {
this.input = input;
}
public String getOperator() {
return operator;
}
public void setOperator(String operator) {
this.operator = operator;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getOperand() {
return operand;
}
public void setOperand(String operand) {
this.operand = operand;
}
public List<Predicates> getPredicates() {
return predicates;
}
public void setPredicates(List<Predicates> predicates) {
this.predicates = predicates;
}
}
解析
ObjectMapper mapper = new ObjectMapper();
Predicates pr = mapper.readValue(json, Predicates.class);
2条答案
按热度按时间lymnna711#
我不知道你想用你的
unpackNested
方法实现什么。Jackson已经可以将JSON中的属性绑定到对象中,并且可以很好地处理递归属性。我只是删除了你的
unpackNested
方法,并在你提供的输入上运行了你的代码:对象
pr
包含完整的json,包括嵌套的子 predicate 。(我用jackson databind 2.11.2运行代码)。如果你的属性没有被自动检测到,用
@JsonProperty
注解你的getter:但除此之外,不需要采取额外的步骤。Jackson已经可以解包嵌套对象,只需删除您的(奇怪的)
unpackNested
方法,让Jackson完成它的工作。p8h8hvxi2#