Подтвердить что ты не робот

Как отправить POST полезную нагрузку JSON на @RequestParam в Spring MVC

Я использую 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, но тогда я теряю возможность разделения POST-аргументов вне тела JSON.

Есть ли способ в Spring MVC "смешивать" обычные аргументы POST и объекты JSON?

4b9b3361

Ответ 1

Да, возможно отправить и параметры, и тело с помощью метода 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"}'

наслаждаться

Ответ 2

Вы можете сделать это, зарегистрировав Converter из 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);
        }
    }
}

Ответ 3

Вы можете использовать RequestEntity.

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

Ответ 4

Пользователь:

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


    //getter, setter ...
}

JSON:

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

Вы можете использовать @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";
}