Spring @RequestBody 未映射到自定义对象
Spring @RequestBody not mapping to custom Object
我有一个名为 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://jsonlint.com检查了JSON的有效性):
{
"query":{
"field1":"value1",
"field2":"value2"
},
"projections":["field3, field4"],
"limit":3
}
结果是:对象 "example" 的投影和限制已正确设置,但查询为空 JSON 对象(非空)。如果我不发送字段查询,对象 "example" 上的 JSONObject 变量为空。
我不明白为什么字段查询没有设置好。我想 Spring 将 @RequestBody json 映射到一个 ExampleObject。
Spring(尤其是 Jackson)不知道如何反序列化 JSONObject
。您可以改用 com.fasterxml.jackson.core.JsonNode
。
我有一个名为 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://jsonlint.com检查了JSON的有效性):
{
"query":{
"field1":"value1",
"field2":"value2"
},
"projections":["field3, field4"],
"limit":3
}
结果是:对象 "example" 的投影和限制已正确设置,但查询为空 JSON 对象(非空)。如果我不发送字段查询,对象 "example" 上的 JSONObject 变量为空。
我不明白为什么字段查询没有设置好。我想 Spring 将 @RequestBody json 映射到一个 ExampleObject。
Spring(尤其是 Jackson)不知道如何反序列化 JSONObject
。您可以改用 com.fasterxml.jackson.core.JsonNode
。