当前位置: 首页 > 知识库问答 >
问题:

Spring Boot控制器调用不支持内容类型'application/json;charset=UTF-8'

长孙泉
2023-03-14
@RequestMapping(value = "/addBook", method = RequestMethod.POST, produces = "application/json")
    @ApiOperation(value = "Add a new Book in the Library", response = BookDTO.class)
    @ApiResponses(value = { @ApiResponse(code = 409, message = "Conflict: the book already exist"),
            @ApiResponse(code = 201, message = "Created: the book is successfully inserted"),
            @ApiResponse(code = 304, message = "Not Modified: the book is unsuccessfully inserted") })
    public ResponseEntity<BookDTO> createNewBook(@RequestBody BookDTO bookDTORequest) {
        // , UriComponentsBuilder uriComponentBuilder
        Book existingBook = bookService.findBookByIsbn(bookDTORequest.getIsbn());
        if (existingBook != null) {
            return new ResponseEntity<BookDTO>(HttpStatus.CONFLICT);
        }
        Book bookRequest = mapBookDTOToBook(bookDTORequest);
        Book book = bookService.saveBook(bookRequest);
        if (book != null && book.getId() != null) {
            BookDTO bookDTO = mapBookToBookDTO(book);
            return new ResponseEntity<BookDTO>(bookDTO, HttpStatus.CREATED);
        }
        return new ResponseEntity<BookDTO>(HttpStatus.NOT_MODIFIED);
 
    }
 
    private BookDTO mapBookToBookDTO(Book book) {
        ModelMapper mapper = new ModelMapper();
        BookDTO bookDTO = mapper.map(book, BookDTO.class);
        if (book.getCategory() != null) {
            bookDTO.setCategory(new CategoryDTO(book.getCategory().getCode(), book.getCategory().getLabel()));
        }
        return bookDTO;
    }
 
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonDeserialize(using = BookDTODeserializer.class)
@Data
@AllArgsConstructors
public class BookDTO implements Comparable<BookDTO> {
    @ApiModelProperty(value = "Book id")
    private Integer id;
 
    @ApiModelProperty(value = "Book title")
    private String title;
 
    @ApiModelProperty(value = "Book isbn")
    private String isbn;
 
    @ApiModelProperty(value = "Book release date by the editor")
    private LocalDate releaseDate;
 
    @ApiModelProperty(value = "Book register date in the library")
    private LocalDate registerDate;
 
    @ApiModelProperty(value = "Book total examplaries")
    private Integer totalExamplaries;
 
    @ApiModelProperty(value = "Book author")
    private String author;
 
    @ApiModelProperty(value = "Book category")
    private CategoryDTO category;
 
 
    @Override
    public int compareTo(BookDTO o) {
        return title.compareToIgnoreCase(o.getTitle());
    }
 
    public BookDTO() {
        super();
    }
 
}
 
@Entity
@Data
@AllArgsConstructors
public class Book {
    private static final long serialVersionUID = 425345L;
 
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
 
    private String title;
    private String author;
    private String publisher;
    private String publicationDate;
    private String language;
    private String category;
    private int numberOfPages;
    private String format;
    private String isbn;
    private double shippingWeight;
    private double listPrice;
    private double ourPrice;
    private boolean active = true;
 
    @Column(columnDefinition = "text")
    private String description;
    private int inStockNumber;
 
    @Transient
    private MultipartFile bookImage;
}
 
@Data
@AllArgsConstructors
@JsonDeserialize(using = CategoryDTODeserializer.class)
public class CategoryDTO implements Comparable<CategoryDTO> {
    public CategoryDTO() {
    }
 
    public CategoryDTO(String code, String label) {
        super();
        this.code = code;
        this.label = label;
    }
 
    @ApiModelProperty(value = "Category code")
    private String code;
 
    @ApiModelProperty(value = "Category label")
    private String label;
 
}
 
@Entity
@Table(name = "CATEGORY")
public class Category {
    public Category() {
    }
 
    public Category(String code, String label) {
        super();
        this.code = code;
        this.label = label;
    }
 
    private String code;
 
    private String label;
 
    @Id
    @Column(name = "CODE")
    public String getCode() {
        return code;
    }
 
    public void setCode(String code) {
        this.code = code;
    }
 
    @Column(name = "LABEL", nullable = false)
    public String getLabel() {
        return label;
    }
 
    public void setLabel(String label) {
        this.label = label;
    }
}
 
public class BookDTODeserializer extends StdDeserializer<BookDTO> {
 
    @Override
    public BookDTO deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        // TODO Auto-generated method stub
        JsonNode node = p.getCodec().readTree(p);
        Integer id = (Integer) ((IntNode) node.get("id")).numberValue();
        String title = node.get("title").asText();
        String isbn = node.get("isbn").asText();
        LocalDate releaseDate = LocalDate.parse(node.get("releaseDate").asText());
        LocalDate registerDate = LocalDate.parse(node.get("registerDate").asText());
        Integer totalExamplaries = (Integer) ((IntNode) node.get("totalExamplaries")).numberValue();
        String author = node.get("author").asText();
        String codeCategory = node.get("code").asText();
        String labelCategory = node.get("label").asText();
 
        return new BookDTO(id, title, isbn, releaseDate, registerDate, totalExamplaries, author,
                new CategoryDTO(codeCategory, labelCategory));
        // return null;
    }
 
    public BookDTODeserializer(Class<?> vc) {
        super(vc);
        // TODO Auto-generated constructor stub
    }
 
    public BookDTODeserializer(JavaType valueType) {
        super(valueType);
        // TODO Auto-generated constructor stub
    }
 
    public BookDTODeserializer(StdDeserializer<?> src) {
        super(src);
        // TODO Auto-generated constructor stub
    }
 
}
 
public class CategoryDTODeserializer extends StdDeserializer<CategoryDTO> {
 
    @Override
    public CategoryDTO deserialize(JsonParser p, DeserializationContext ctxt)
            throws IOException, JsonProcessingException {
        JsonNode node = p.getCodec().readTree(p);
        String codeCategory = node.get("code").asText();
        String labelCategory = node.get("label").asText();
        return new CategoryDTO(codeCategory, labelCategory);
    }
 
    public CategoryDTODeserializer(Class<?> vc) {
        super(vc);
        // TODO Auto-generated constructor stub
    }
 
    public CategoryDTODeserializer(JavaType valueType) {
        super(valueType);
        // TODO Auto-generated constructor stub
    }
 
    public CategoryDTODeserializer(StdDeserializer<?> src) {
        super(src);
        // TODO Auto-generated constructor stub
    }
 
}

我的角码

saveBook(book: Book): Observable<Book>{
      let headers = new HttpHeaders();
      headers.append('content-type', 'application/json');
      headers.append('accept', 'application/json');
      return this.http.post<Book>(environment.apiUrl+'/rest/book/api/addBook', book, {headers: headers});
     }

你有什么想法吗?

共有1个答案

窦宏旷
2023-03-14

根据警告/错误消息,您缺少以下内容:

  1. 找不到默认构造函数;嵌套异常是java.lang.NosuchMethodException:com.biblio.fr.biblio.entite.BookdTodeRializer

用@noargsconstructor声明BookDTODeserializer

 类似资料:
  • 嗨,有人能帮我处理这个错误吗?当我使用邮递员发送邮件请求时,这里是我的控制器 这就是我使用postman发送json的方式 我正在尝试搜索如何修复它,但错误仍然存在 编辑:这是邮递员的标题 提前致谢

  • @PostMapping public UserResponse createUser(@RequestBody UserRequest userDetail){ 这是我收到的错误代码 } 我尝试了很多不同的方法仍然没有得到解决方案这是来自邮递员的图片来自邮递员的图片

  • 我正在使用JavaSpring框架创建一个时事通讯API。每当我以请求模型的帖子的形式访问API时,我都会得到这个例外组织。springframework。网状物HttpMediaTypeNotSupportedException。 这是我的时事通讯模型 这是我的NewsletterMailerList模型 我给包含类型作为应用程序/json。我是新来做这种事情的。请帮助我为什么会出现这个错误。如

  • 当我在localhost:8080/api/users上做一个POST请求来创建一个新用户时,我会得到以下错误: 是请求的主体,选择JSON(应用程序/JSON)。即使我删除角色并将其保持为空,它也会给出相同的错误。 标题的内容类型也是application/json。 这是我的控制器: UserService中的createUser函数: 这是我的用户类:

  • 问题内容: 我写了下面的@Controller方法 请求失败并出现以下错误 [PS:泽西岛要友好得多,但鉴于此处的实际限制,现在无法使用它] 问题答案: 问题在于,当我们使用application / x-www-form-urlencoded时,Spring不会将其理解为RequestBody。因此,如果要使用它,则必须删除@RequestBody批注。 然后尝试以下操作:

  • 问题内容: 基于Spring @Controller对x-www-form-urlencoded的问的答案 我写了下面的@Controller方法 失败的请求因以下错误 [PS:Jersey要友好得多,但鉴于这里的实际限制,现在无法使用它] 问题答案: 问题在于,当我们使用 application / x-www-form-urlencoded时 ,Spring不会将其理解为RequestBody