Spring Boot - Post 单个 string/enum 到 REST 服务

Sprint Boot - Post a single string/enum to a REST service

我正在尝试通过 Spring 引导将单个字符串发送到 REST API,但我一直收到 400:错误请求。我通过 postman 确认这个 json 被 API:

接受
{
    "currency": "USD"
}

我为这个服务写了下面一段代码post:

public Account createAccount(Currency currency)
{
        Account account = (Account) restTemplate.postForObject(url, currency.toString(), Account.class);
        return account;
}

货币枚举如下:

public enum Currency 
{
    USD, EUR
}

我尝试将其作为枚举值和字符串值发送,none 成功了。

您应该创建一个 class 来封装枚举,例如:

public class CreateAccountRequest {

  private final Currency currency;

  public CreateAccountRequest(Currency currency) {
    this.currency = currency; 
  }

  public Currency getCurrency() {

  }
}

然后当你执行 postForObject:

restTemplate.postForObject(url, createAccountRequest, Account.class);