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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38262055/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 20:08:41  来源:igfitidea点击:

How to POST a JSON payload to a @RequestParam in Spring MVC

javarestspring-mvcspring-boot

提问by Luciano

I'm using Spring Boot(latest version, 1.3.6) and I want to create a REST endpointwhich accepts a bunch of arguments and a JSON object. Something like:

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

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

In the Spring controller I'm currently doing:

在我目前正在做的 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) {

  ...
}

The jsonargument doesn't get serialized into a Person object. I get a

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

400 error: the parameter json is not present.

Obviously, I can make the jsonargument as String and parse the payload inside the controller method, but that kind of defies the point of using Spring MVC.

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

It all works if I use @RequestBody, but then I loose the possibility to POST separate arguments outside the JSON body.

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

Is there a way in Spring MVC to "mix" normal POST arguments and JSON objects?

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

采纳答案by Mosd

Yes,is possible to send both params and body with a post method: Example server side:

是的,可以使用 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;
}

and on your client:

并在您的客户端上:

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"}'

Enjoy

享受

回答by Rich

You can do this by registering a Converterfrom Stringto your parameter type using an auto-wired ObjectMapper:

您可以通过使用 auto-wired将Converterfrom注册String到您的参数类型来做到这一点ObjectMapper

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 Date convert(String source) {
        try {
            return objectMapper.readValue(source, Person.class);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

回答by egemen

you can use RequestEntity.

你可以使用RequestEntity。

public Person getPerson(RequestEntity<Person> requestEntity) {
    return requestEntity.getBody();
}

回答by Sorul

User:

用户:

 @Entity
public class User {
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Integer userId;
    private String name;
    private String password;
    private String email;


    //getter, setter ...
}

JSON:

JSON:

{"name":"Sam","email":"[email protected]","password":"1234"}

You can use @RequestBody:

您可以使用@RequestBody

@PostMapping(path="/add")
public String addNewUser (@RequestBody User user) {
    User u = new User(user.getName(),user.getPassword(),user.getEmail());
    userRepository.save(u);
    return "User saved";
}