首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何将JSON有效负载发布到Spring MVC中的@RequestParam

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

Stack Overflow用户
提问于 2016-07-08 16:21:20
回答 4查看 60K关注 0票数 24

我正在使用JSON (最新版本,1.3.6),我想创建一个JSON端点,它接受一堆参数和一个JSON。类似于:

代码语言:javascript
复制
curl -X POST http://localhost:8080/endpoint \
-d arg1=hello \
-d arg2=world \
-d json='{"name":"john", "lastNane":"doe"}'

在Spring控制器中,我目前正在执行以下操作:

代码语言:javascript
复制
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对象。我得到了一个

代码语言:javascript
复制
400 error: the parameter json is not present.

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

如果我使用@RequestBody就可以了,但是之后我就不可能在JSON主体之外发布单独的参数了。

在Spring MVC中有没有办法“混合”正常的POST参数和对象?

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2016-07-08 18:07:58

可以,可以使用post方法同时发送params和body :示例服务器端:

代码语言:javascript
复制
@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;
}

在你的客户端上:

代码语言:javascript
复制
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"}'

尽情享受

票数 26
EN

Stack Overflow用户

发布于 2018-05-29 06:59:06

为此,可以使用自动连接的ConverterString中的ObjectMapper注册到您的参数类型

代码语言:javascript
复制
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);
        }
    }
}
票数 10
EN

Stack Overflow用户

发布于 2019-07-15 19:37:27

您可以使用RequestEntity。

代码语言:javascript
复制
public Person getPerson(RequestEntity<Person> requestEntity) {
    return requestEntity.getBody();
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38262055

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档