我是 SB 新手,并試圖提高我的技能。我做了一個小API專案,其中我有帳戶余額屬性的帳號,該專案的目標是將帳戶余額屬性中的金額與相應的帳號相加。
我被困在我需要從實際上不是任何類的一部分的數量變數中獲取值的地方。如果您認為標題與主題不符,任何人都可以更改標題。我在下面提到的課程,你會發現我的努力沒有用,因為它似乎一團糟。如果有人可以糾正或給我相同問題所在的參考堆疊,我將不勝感激。
賬號.java
private Long id;
private int accountNumber;
private BigDecimal accountBalance;
帳戶庫
public interface AccountDao extends CrudRepository<Account, Long> {
Account findByAccountNumber(int accountNumber);
}
賬戶服務
public interface AccountService {
void deposit(int accountNumber, String accountType, double amount);
} // these fields are not related to class field, I took this to send data to API
賬戶服務實作
public void deposit(String accountType, int accountNumber, double amount) {
if (accountType.equalsIgnoreCase("Permanent")) {
Account account = accountRepository.findByAccountNumber(accountNumber);
account.setAccountBalance(account.getAccountBalance().add(new
BigDecimal(amount)));
accountDao.save(account);
帳戶控制器
@PostMapping("/deposit")
public ResponseEntity<Object> depositPost(@RequestBody double amount, String accountType,
int accountNumber, Account account){
accountService.deposit(accountType, accountNumber,
Double.parseDouble(String.valueOf(amount)));
return ResponseEntity.ok("Record has been entered");
}
我收到的錯誤是:
2021-10-21 20:19:58.660 WARN 22892 --- [nio-8088-exec-1]
.w.s.m.s.DefaultHandlerExceptionResolver : Resolved
[org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error:
Cannot deserialize value of type `double` from Object value (token
`JsonToken.START_OBJECT`); nested exception is
com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize value of
type `double` from Object value (token `JsonToken.START_OBJECT`)
at [Source: (PushbackInputStream); line: 1, column: 1]]
uj5u.com熱心網友回復:
問題是您的 POST 正文。我猜你正在發送類似于以下內容:
{
"amount": 1000
}
這是一個無法反序列化為簡單double引數的 JSON 物件。您需要創建一個相應的類,如下所示:
public class AccountDto {
private double amount;
// constructor, getters, setters
}
現在你需要在你的控制器中使用它:
@PostMapping("/deposit")
public ResponseEntity<Object> depositPost(@RequestBody AccountDto accountDto, String accountType, int accountNumber, Account account){
accountService.deposit(accountType, accountNumber, accountDto.getAmount());
return ResponseEntity.ok("Record has been entered");
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/331720.html
上一篇:如何在屬于AbstractConsumerSeekAware類的SpringKafka中實作seekToEnd()?
