@RequestBody映射复杂的json对象

时间:2018-05-17 07:41:34

标签: java json spring rest

我需要将json转换为@RequestBody的java对象。

{
    "entity": {
        "id": 3,
        "name": "james"
    },
    "conjunction": "OR",
    "conditions": [
        {
            "operation": "equalTo",
            "dataKey": "department",
            "dataType": "string",
            "value": "abc"
        },
        {
            "operation": "notEqualTo",
            "dataKey": "ID",
            "dataType": "number",
            "value": "100"
        },
        {
            "operation": "notEqualTo",
            "dataKey": "name",
            "dataType": "strubg",
            "value": "jack"
        },
        {
            "operation": "between",
            "dataKey": "END_DATE",
            "dataType": "date",
            "value1": "20180502",
            "value2": "20180519"
        }
    ]
}

数组中的前三个元素对应于下面的java对象。

public class ComparisonCondition extends Condition {
    private String value;
}

最后一个元素对应于对象下方。

public class BetweenCondition extends Condition {
    private String value1;
    private String value2;
}

他们都从下面的对象继承。

public class Condition {
    private String dataKey;
    private String dataType;
    private String operation;
}

spring mvc方法如下。

@RequestMapping(value = RequestAction.FILTER, method = RequestMethod.POST)
public List<Student>  filter(
        @RequestBody  Filter<Student> filterConfig) {   
    return null;

}

Filter对象位于下方。

public class Filter<T> {
    private String conjunction;
    private T entity;
    private List<Condition> conditions;
}

如何成功将json映射到java对象? 目前报告"Could not read JSON: Unrecognized field "value" (class com.ssc.rest.entity.Condition), not marked as ignorable (3 known properties: "dataType", "dataKey", "operation"])

2 个答案:

答案 0 :(得分:0)

对于您的错误,如果杰克逊解析器不知道某个字段,则会抛出异常。

您可以通过添加注释来避免它:

@JsonIgnore(ignoreUnknown=true)

在目标对象上。

对于您的映射,我建议您创建一个与您的json输入相对应的对象,然后手动映射到目标对象。

答案 1 :(得分:0)

您正在JSON中传递4个变量用于COndition

{
    "operation": "equalTo",
    "dataKey": "department",
    "dataType": "string",
    "value": "abc"
},

但您的Java POJO只有3个变量

public class Condition {
    private String dataKey;
    private String dataType;
    private String operation;
}

只需添加value,它就可以正常使用。

底线是: POJO类应该包含以JSON传递的所有字段。

顺便说一句,你的异常就是在说同样的事情

Unrecognized field "value"

编辑1:

我错过了BetweenCondition和ComparisonCondition

您可以使用Sub Class属性定义案例Condition中的基类,并希望它可以正常工作

@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "javaclass")
@JsonSubTypes({
    @Type(value = ComparisonCondition.class),
    @Type(value = BetweenCondition.class)
})

public class Condition {
    private String dataKey;
    private String dataType;
    private String operation;
}