如何在 Spring MVC 中将 JSON 有效负载发布到 @RequestParam

新手上路,请多包涵

我正在使用 Spring Boot (最新版本, 1.3.6 ),我想创建一个 REST 端点,它接受一堆参数和一个 JSON 对象。就像是:

 curl -X POST http://localhost:8080/endpoint \
-d arg1=hello \
-d arg2=world \
-d json='{"name":"john", "lastNane":"doe"}'

在我目前正在做的 Spring 控制器中:

 public SomeResponseObject endpoint(
@RequestParam(value="arg1", required=true) String arg1,
@RequestParam(value="arg2", required=true) String arg2,
@RequestParam(value="json", required=true) Person person) {

  ...
}

json 参数未序列化为 Person 对象。我得到一个

400 error: the parameter json is not present.

显然,我可以将 json 参数设为 String 并在控制器方法中解析有效负载,但这违背了使用 Spring MVC 的要点。

如果我使用 @RequestBody 一切正常,但随后我失去了在 JSON 主体之外发布单独参数的可能性。

Spring MVC 中有没有办法“混合”普通的 POST 参数和 JSON 对象?

原文由 Luciano 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 327
2 个回答

是的,可以使用 post 方法同时发送参数和正文:服务器端示例:

 @RequestMapping(value ="test", method = RequestMethod.POST)
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public Person updatePerson(@RequestParam("arg1") String arg1,
        @RequestParam("arg2") String arg2,
        @RequestBody Person input) throws IOException {
    System.out.println(arg1);
    System.out.println(arg2);
    input.setName("NewName");
    return input;
}

在你的客户上:

 curl -H "Content-Type:application/json; charset=utf-8"
     -X POST
     'http://localhost:8080/smartface/api/email/test?arg1=ffdfa&arg2=test2'
     -d '{"name":"me","lastName":"me last"}'

享受

原文由 Mosd 发布,翻译遵循 CC BY-SA 4.0 许可协议

您可以通过使用自动连接的 ObjectMapperConverterString 注册到您的参数类型来执行此操作:

 import org.springframework.core.convert.converter.Converter;

@Component
public class PersonConverter implements Converter<String, Person> {

    private final ObjectMapper objectMapper;

    public PersonConverter (ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @Override
    public Person convert(String source) {
        try {
            return objectMapper.readValue(source, Person.class);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

原文由 Rich 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题