Spring @RequestBody没有映射到自定义对象

时间:2017-01-28 21:30:27

标签: json spring spring-restcontroller

我有一个名为Example的自定义对象,它有一个org.json.JSONObject作为mongo查询。

public class ExampleObject {

private JSONObject query;
private String[] projections;
private Number limit;

// Constructors, getters and setters

}

我正在使用这样的REST控制器:

@RestController
@RequestMapping("/example")
public class ExampleRestController {

@RequestMapping(value = "/search", method = RequestMethod.POST)
@ResponseBody
public String example(@RequestBody ExampleObject example) {

    return "This is an example";
}

然后,我向Postman提出以下要求:

  

发布到http://localhost:8080/example/search

正文如下(我已使用http://jsonlint.com检查了JSON的有效性):

{
"query":{
    "field1":"value1",
    "field2":"value2"
    },
"projections":["field3, field4"],
"limit":3
}

结果是:对象“example”的投影和限制已正确设置,但查询是空的JSONObject(非null)。如果我不发送字段查询,则对象“example”上的JSONObject变量为null。

我不明白为什么字段查询没有设置好。我想Spring将@RequestBody json映射到ExampleObject。

1 个答案:

答案 0 :(得分:1)

Spring(特别是Jackson)不知道如何反序列化JSONObject。您可以改为使用com.fasterxml.jackson.core.JsonNode

相关问题