개발일지/2023_한이음

[개발]🚨ERROR - org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error

기억지기 개발자 2023. 5. 31. 22:13

🛤️상황

@RestController
@CrossOrigin(origins = "http://localhost:3000", methods = {RequestMethod.OPTIONS, RequestMethod.DELETE, RequestMethod.GET, RequestMethod.POST, RequestMethod.PUT})
@RequestMapping("/review")
public class ReviewController {
    private final ReviewService reviewService;

    public ReviewController(ReviewService reviewService) {
        this.reviewService = reviewService;
    }

    // 리뷰 등록
    @PostMapping("/save")
    public ResponseEntity save(@RequestBody Review review) {
        return ResponseEntity.ok().body(reviewService.save(review));
    }

    //해당 학교애 대한 전체 리뷰 보여주기
    @GetMapping("/list")
    public ResponseEntity list(Long schoolId) {
        return ResponseEntity.ok().body(reviewService.findAll(schoolId));
    }

    //update
    @PutMapping(value = "/update/{id}")
    public ResponseEntity<Review> update(@RequestBody ReviewDTO dto, @PathVariable Long id) {
        Optional<Review> reviewdto = this.reviewService.update(id, dto);
        return new ResponseEntity(reviewdto, HttpStatus.OK);
    }

    //delete
    @DeleteMapping(value = "/delete/{id}")
    public void delete(@PathVariable Long id) {
        reviewService.delete(id);
    }
}

위와 같이 코드를 구성하였다. 며칠 전에 post men으로 테스트했을 때는 모두 문제없이 진행되었는데 다시 테스트해 보니 아래와 같은 오류가 생겼다.. post men에서는 400번대 오류가 발생했다. 거의 2시간 동안 해결을 못했다...

2023-05-31 15:58:49.346 WARN 616 --- [nio-8080-exec-4] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot construct instance of `hanium.highwayspring.school.School` (although at least one Creator exists): no int/Int-argument constructor/factory method to deserialize from Number value (1); nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of `hanium.highwayspring.school.School` (although at least one Creator exists): no int/Int-argument constructor/factory method to deserialize from Number value (1)<EOL> at [Source: (org.springframework.util.StreamUtils$NonClosingInputStream); line: 10, column: 17] (through reference chain: hanium.highwayspring.review.Review["schoolId"])]

🌸과정

No int/Int-argument constructor/factory method to deserialize from Number value (1):  ➡️ "int 또는 Int 타입의 인자를 받는 생성자 또는 팩토리 메서드가 없어서 숫자 값 (1)을 역직렬화할 수 없음." 나는 직렬화/역직렬화라는 것을 처음 들어봤다.

 

Java 객체 직렬화(Serialization) 와 역직렬화(Deserialization)

직렬화, 역직렬화란? 객체지향 언어인 Java는 프로그램의 모든 데이터들이 객체로 이루어져 있다고 봐도 무방하다. ​그렇다면 Java로 만든 프로그램의 데이터(객체)를 외부로 전송하려면 어떻게

kwangkyun-world.tistory.com

하지만 위의 블로그의 내용과는 다르게 Serializable 인터페이스를 implements 해도 해결이 되지 않았다.😂😂😂

팀원에게 물어보니까 내 코드에 아주 초보적인 문제가 있었다... 

받아오는 값에서 DTO가 아니라 entity 클래스를 바로 사용해 버린 것이어따... 이게 역직렬화랑 정확히 무슨 연관이 있는 건지, 아니먄 역직렬화와는 무관하게 애초부터 이 문제였을지는 모르겠다..

🗝️해결

아래와 같이 매개변수를 DTO로 변경하니까 해결이 되었다.