【问题标题】:How to inject single json parameter value in @PostMapping如何在@PostMapping 中注入单个 json 参数值
【发布时间】:2018-07-17 11:42:41
【问题描述】:

我有一个简单的 POST servlet,并且只想注入 JSON 请求的一个属性:

@RestController
public class TestServlet {
    @PostMapping(value = "/test", consumes = APPLICATION_JSON_VALUE)
    public String test(@Valid @NotBlank @RequestBody String test) {
        return test;
    }
}

请求:

{
    "test": "random value",
    "some": "more"
}

结果:test 参数包含整个 json,而不仅仅是参数值。为什么?我怎样才能在不引入额外 Bean 的情况下 实现这一目标?

【问题讨论】:

    标签: java json spring spring-web


    【解决方案1】:

    你不能指望 Spring 猜测你想要解析 json 来提取“test”字段。

    如果您不想要额外的 bean,请使用 Map<String, String> 并使用“test”键获取值:

    @RestController
    public class TestServlet {
        @PostMapping(value = "/test", consumes = APPLICATION_JSON_VALUE)
        public String test(@Valid @NotBlank @RequestBody Map<String, String> body) {
            return body.get("test");
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-24
      • 2017-11-16
      相关资源
      最近更新 更多