【问题标题】:Spring @RequestBody not mapping to custom ObjectSpring @RequestBody 未映射到自定义对象
【发布时间】:2017-01-28 21:30:26
【问题描述】:

我有一个名为 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
}

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

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

【问题讨论】:

  • 我怀疑 Jackson 不知道如何反序列化 JSONObject。你可以试试com.fasterxml.jackson.core.JsonNode吗?
  • 使用 JsonNode 可以正常工作!谢谢!!

标签: json spring spring-restcontroller


【解决方案1】:

Spring(尤其是 Jackson)不知道如何反序列化 JSONObject。你可以改用com.fasterxml.jackson.core.JsonNode

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-29
    • 2017-03-16
    • 2017-08-12
    • 1970-01-01
    • 2019-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多