Не удалось преобразовать значение типа «java.lang.String» в требуемый тип «java.time.LocalDate»; - PullRequest
1 голос
/ 29 марта 2019

Как и в теме, я хочу получить дату в качестве параметра.У меня есть эта зависимость:

<dependency>
            <groupId>com.fasterxml.jackson.datatype</groupId>
            <artifactId>jackson-datatype-jsr310</artifactId>
        </dependency>

Мой URL выглядит так:

http://localhost:8080/userProducts/2?date=2019-3-29

Мой класс контроллера выглядит так:

package trainingapp.userproduct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;
import trainingapp.calculations.NutrientsCalculationFacade;
import trainingapp.historysystemofmeals.HistorySystemService;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

@RestController
public class UserProductController {

    private final NutrientsCalculationFacade userProductCalculationFacade;
    private final UserProductFindOperationService userProductFindOperationService;
    private final HistorySystemService historySystemService;

    @Autowired
    public UserProductController(NutrientsCalculationFacade userProductCalculationFacade, UserProductFindOperationService userProductFindOperationService, HistorySystemService historySystemService) {
        this.userProductCalculationFacade = userProductCalculationFacade;
        this.userProductFindOperationService = userProductFindOperationService;
        this.historySystemService = historySystemService;
    }

    //yyyy-MM-dd
    @GetMapping("/userProducts/{userID}")
    public String getAllEatenSummedNutrientsByGivenIDInParticularDay(@PathVariable int userID,
                                                                     @RequestParam("date")
                                                                     @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate date) {
        return historySystemService.getAllEatenSummedNutrientsByGivenIDInParticularDay(userID, date);
    }
}

Я получил ошибку:

{
    "timestamp": "2019-03-29T15:22:44.640+0000",
    "status": 400,
    "error": "Bad Request",
    "message": "Failed to convert value of type 'java.lang.String' to required type 'java.time.LocalDate'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [@org.springframework.web.bind.annotation.RequestParam @org.springframework.format.annotation.DateTimeFormat java.time.LocalDate] for value '2019-3-29'; nested exception is java.lang.IllegalArgumentException: Parse attempt failed for value [2019-3-29]",
    "path": "/userProducts/2"
}

Что я должен изменить или добавить?Я пытался решить эту проблему с помощью: Как использовать LocalDateTime RequestParam в Spring?Я получил сообщение «Не удалось преобразовать строку в LocalDateTime» , но оно не сработало.

1 Ответ

1 голос
/ 29 марта 2019

2019-3-29 - это неверный ввод , а код состояния 400 является точным.См. Документацию DateTimeFormat.ISO#DATE:

Наиболее распространенный формат даты ISO yyyy-MM-dd, например, "2000-10-31".

Таким образом, чтобы соответствовать вышеуказанному формату, ваш ввод должен быть 2019-03-29.

...