我正在開發一個簡單的 CRUD api,但我的 post 方法不起作用,每次發送 json 格式的資料時都會引發此例外
{
"title": "Cannot construct instance of `academy.devdojo.springboot2.requests.AnimePostRequestBody` (although at least one Creator exists): cannot deserialize from Object value (no delegate- or property-based Creator)\n at [Source: (PushbackInputStream); line: 2, column: 5]",
"status": 400,
"details": "JSON parse error: Cannot construct instance of `academy.devdojo.springboot2.requests.AnimePostRequestBody` (although at least one Creator exists): cannot deserialize from Object value (no delegate- or property-based Creator); nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of `academy.devdojo.springboot2.requests.AnimePostRequestBody` (although at least one Creator exists): cannot deserialize from Object value (no delegate- or property-based Creator)\n at [Source: (PushbackInputStream); line: 2, column: 5]",
"developerMessage": "org.springframework.http.converter.HttpMessageNotReadableException",
"timestamp": "2022-01-13T14:45:34.9138659"
}
它僅在發送一個簡單的字串(例如“要保存的某個名稱”)時才有效,而不是
{
"name" : "some name to be saved"
}
這是我的課
物體
@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Builder
public class Anime {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotEmpty(message= "anime name cannot be empty")
private String name;
}
回購協議
public interface AnimeRepository extends JpaRepository<Anime, Long> {
List<Anime> findByName(String name);
}
服務
@Service
@RequiredArgsConstructor
public class AnimeService {
private final AnimeRepository animeRepository;
public Page<Anime> listAll(Pageable pageable) {
return animeRepository.findAll(pageable);
}
public List<Anime> findByName(String name) {
List<Anime> byName = animeRepository.findByName(name);
if (byName.isEmpty()){
throw new BadRequestException("Anime not Found");
}
return byName;
}
public Anime findByIdOrThrowBadRequestException(long id) {
return animeRepository.findById(id)
.orElseThrow(() -> new BadRequestException("Anime not Found"));
}
public Anime save(AnimePostRequestBody animePostRequestBody) {
Anime anime = AnimeMapper.INSTANCE.toAnime(animePostRequestBody);
return animeRepository.save(anime);
}
public void delete(long id) {
animeRepository.delete(findByIdOrThrowBadRequestException(id));
}
public void replace(AnimePutRequestBody animePutRequestBody) {
Anime savedAnime = findByIdOrThrowBadRequestException(animePutRequestBody.getId());
Anime anime = AnimeMapper.INSTANCE.toAnime(animePutRequestBody);
anime.setId(savedAnime.getId());
animeRepository.save(anime);
}
public List<Anime> listAllNonPageable() {
return animeRepository.findAll();
}
}
休息控制器
@RestController
@Api(tags = "Atividades Economicas")
@RequestMapping("animes")
@Log4j2
@RequiredArgsConstructor
public class AnimeController {
private final DateUtil dateUtil;
private final AnimeService animeService;
@ApiOperation(value = "Listar todos")
@GetMapping
public ResponseEntity<Page<Anime>> list(Pageable pageable) {
//log.info(dateUtil.formatLocalDateTimeToDatabaseStyle(LocalDateTime.now()));
return ResponseEntity.ok(animeService.listAll(pageable));
}
@GetMapping(path = "/all")
public ResponseEntity<List<Anime>> listAll() {
//log.info(dateUtil.formatLocalDateTimeToDatabaseStyle(LocalDateTime.now()));
return ResponseEntity.ok(animeService.listAllNonPageable());
}
@ApiOperation(value = "Listar por ID")
@GetMapping(path = "/{id}")
public ResponseEntity<Anime> findById(@PathVariable long id) {
return ResponseEntity.ok(animeService.findByIdOrThrowBadRequestException(id));
}
@ApiOperation(value = "Encontrar pelo nome")
@GetMapping(path = "/find")
public ResponseEntity<List<Anime>> findByName(@RequestParam String name) {
return ResponseEntity.ok(animeService.findByName(name));
}
@PostMapping
public ResponseEntity<Anime> save(@RequestBody @Valid AnimePostRequestBody animePostRequestBody) {
return new ResponseEntity<>(animeService.save(animePostRequestBody), HttpStatus.CREATED);
}
@DeleteMapping(path = "/{id}")
public ResponseEntity<Void> delete(@PathVariable long id) {
animeService.delete(id);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
@PutMapping
public ResponseEntity<Void> replace(@RequestBody AnimePutRequestBody animePutRequestBody) {
animeService.replace(animePutRequestBody);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
}
DTO
@Data
@Builder
public class AnimePostRequestBody {
@NotEmpty(message= "anime name cannot be empty")
private String name;
}
@Data
@Builder
public class AnimePutRequestBody {
private Long id;
private String name;
}
映射器
@Mapper(componentModel = "spring")
public abstract class AnimeMapper {
public static final AnimeMapper INSTANCE = Mappers.getMapper(AnimeMapper.class);
public abstract Anime toAnime(AnimePostRequestBody animePostRequestBody);
public abstract Anime toAnime(AnimePutRequestBody animePutRequestBody);
}
ps put 方法作業正常,盡管它們非常相似。
uj5u.com熱心網友回復:
@Data 是一個方便的快捷注解,將@ToString、@EqualsAndHashCode、@Getter/@Setter 和@RequiredArgsConstructor 的特性捆綁在一起
默認建構式是必需的。添加 lombok 的 @NoArgsConstructor 注釋。
uj5u.com熱心網友回復:
除了 Model 類,DTO 類還應該包含@AllArgsConstructorand @NoArgsConstructor。要將 RequestBody 值映射到 DTO,它將需要建構式,而 @Data 不提供 @AllArgsConstructor 和 @NoArgsConstructor 建構式。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/410416.html
標籤:
上一篇:選擇組合框中的專案時設定操作
