IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Spring Boot Java Discussion :

SpringBoot problème Content type 'application/json;charset=UTF-8' not supported


Sujet :

Spring Boot Java

Vue hybride

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Membre confirmé
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Juin 2012
    Messages
    92
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Haute Garonne (Midi Pyrénées)

    Informations professionnelles :
    Activité : Développeur informatique
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Juin 2012
    Messages : 92
    Par défaut SpringBoot problème Content type 'application/json;charset=UTF-8' not supported
    Bonjour à tous,

    J'ai un problème avec l'envoi de mes données de mon formulaire angulaire vers mon contrôleur Spring boot:

    Je reçois cette erreur :

    WARN 15020 --- [nio-8181-exec-2] .c.j.MappingJackson2HttpMessageConverter : Failed to evaluate Jackson deserialization for type [[simple type, class com.biblio.fr.biblio.entite.BookDTO]]: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.biblio.fr.biblio.entite.BookDTODeserializer': Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.biblio.fr.biblio.entite.BookDTODeserializer]: No default constructor found; nested exception is java.lang.NoSuchMethodException: com.biblio.fr.biblio.entite.BookDTODeserializer.<init>()


    WARN 15020 --- [nio-8181-exec-2] .c.j.MappingJackson2HttpMessageConverter : Failed to evaluate Jackson deserialization for type [[simple type, class com.biblio.fr.biblio.entite.BookDTO]]: com.fasterxml.jackson.databind.JsonMappingException: Class com.biblio.fr.biblio.entite.BookDTODeserializer has no default (no arg) constructor


    WARN 15020 --- [nio-8181-exec-2] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/json;charset=UTF-8' not supported]
    Contrôleur :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    @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
    	}
     
    }
    et mon appel angular :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
     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});
         }
    Avez - vous une idée ?

  2. #2
    Membre chevronné
    Homme Profil pro
    Ingénieur en génie logiciel
    Inscrit en
    Juin 2012
    Messages
    944
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Canada

    Informations professionnelles :
    Activité : Ingénieur en génie logiciel
    Secteur : High Tech - Opérateur de télécommunications

    Informations forums :
    Inscription : Juin 2012
    Messages : 944
    Par défaut
    selon le message, tu aurais pas de constructeur dans ta classe BookDTO

  3. #3
    Membre confirmé
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Juin 2012
    Messages
    92
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Haute Garonne (Midi Pyrénées)

    Informations professionnelles :
    Activité : Développeur informatique
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Juin 2012
    Messages : 92
    Par défaut
    Bonjour,

    J'ai rajouté le constructeur dans la classe BookDTO, mais j'ai maintenant cette erreur :
    Request processing failed; nested exception is org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement
    Caused by: java.sql.SQLIntegrityConstraintViolationException: Duplicata du champ 'M' pour la clef 'PRIMARY'

    Le contexte est celui-ci : J'ai deux classes Book et Category avec une relation OneToMany et ManyToOne : Un Book correspond à une Category( et une Category correspond à plusieurs Book. Côté Front, je selctionne une categorie parmi les 4 présentes en BD (Cuisine,Jeunesse, Informatique et Mathematique).Lors de l'insertion d'un Book(livre) , je sélectionne une categorie pour faire une jointure, mais malheureusement il veut insérer aussi catégorie et cela crée une erreur. Comment corriger cela.

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338
    339
    340
    341
    342
    343
    344
    345
    346
    347
    348
    349
    350
    351
    352
    353
    354
    355
    356
    357
    358
    359
    360
    361
    362
    363
    364
    365
    366
    367
    368
    369
    370
    371
    372
    373
    374
    375
    376
    377
    378
    379
    380
    381
    382
    383
    384
    385
    386
    387
    388
    389
    390
    391
    392
    393
    394
    395
    396
    397
    398
    399
    400
    401
    402
    403
    404
    405
    406
    407
    408
    409
    410
    411
    412
    413
    414
    415
    416
    417
    418
    419
    420
    421
    422
    423
    424
    425
    426
    427
    428
    429
    430
    431
    432
    433
    434
    435
    436
    437
    438
    439
    440
    441
    442
    443
    444
    445
    446
    447
    448
    449
    450
    451
    452
    453
    454
    455
    456
    457
    458
    459
    460
    461
    462
    463
    464
    465
    466
    467
    468
    469
    470
    471
    472
    473
    474
    475
    476
    477
    478
    479
    480
    481
    482
    483
    484
    485
    486
    487
    488
    489
    490
    491
    492
    493
    494
    495
    496
    497
    498
    499
    500
    501
    502
     
    @Entity
    @Table(name = "CATEGORY")
    public class Category {
    	public Category() {
    	}
     
    	public Category(String code, String label) {
    		super();
    		this.code = code;
    		this.label = label;
    	}
     
    	@Id
    	@GeneratedValue(strategy = GenerationType.AUTO)
    	@Column(name = "ID")
    	private Integer id;
     
    	private String code;
     
    	private String label;
    	@OneToMany(mappedBy = "category", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    	private Set<Book> book;
     
    	@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 Integer getId() {
    		return id;
    	}
     
    	public void setId(Integer id) {
    		this.id = id;
    	}
     
    	public Set<Book> getBook() {
    		return book;
    	}
     
    	public void setBook(Set<Book> book) {
    		this.book = book;
    	}
     
    }
     
     
    @Entity
    @Table(name = "BOOK")
    public class Book {
    	private Integer id;
     
    	private String title;
     
    	private String isbn;
     
    	private LocalDate releaseDate;
     
    	private LocalDate registerDate;
     
    	private Integer totalExamplaries;
     
    	private String author;
     
    	private Category category;
     
    	Set<Loan> loans = new HashSet<Loan>();
     
    	@Id
    	@GeneratedValue(strategy = GenerationType.AUTO)
    	@Column(name = "BOOK_ID")
    	public Integer getId() {
    		return id;
    	}
     
    	public void setId(Integer id) {
    		this.id = id;
    	}
     
    	@Column(name = "TITLE", nullable = false)
    	public String getTitle() {
    		return title;
    	}
     
    	public void setTitle(String title) {
    		this.title = title;
    	}
     
    	@Column(name = "ISBN", nullable = false, unique = true)
    	public String getIsbn() {
    		return isbn;
    	}
     
    	public void setIsbn(String isbn) {
    		this.isbn = isbn;
    	}
     
    	@Column(name = "RELEASE_DATE", nullable = false)
    	public LocalDate getReleaseDate() {
    		return releaseDate;
    	}
     
    	public void setReleaseDate(LocalDate releaseDate) {
    		this.releaseDate = releaseDate;
    	}
     
    	@Column(name = "REGISTER_DATE", nullable = false)
    	public LocalDate getRegisterDate() {
    		return registerDate;
    	}
     
    	public void setRegisterDate(LocalDate registerDate) {
    		this.registerDate = registerDate;
    	}
     
    	@Column(name = "TOTAL_EXAMPLARIES")
    	public Integer getTotalExamplaries() {
    		return totalExamplaries;
    	}
     
    	public void setTotalExamplaries(Integer totalExamplaries) {
    		this.totalExamplaries = totalExamplaries;
    	}
     
    	@Column(name = "AUTHOR")
    	public String getAuthor() {
    		return author;
    	}
     
    	public void setAuthor(String author) {
    		this.author = author;
    	}
     
    	@ManyToOne(optional = false, cascade = CascadeType.ALL)
    	@JoinColumn(name = "CAT_CODE", referencedColumnName = "ID")
    	public Category getCategory() {
    		return category;
    	}
     
    	public void setCategory(Category category) {
    		this.category = category;
    	}
     
    	@OneToMany(fetch = FetchType.LAZY, mappedBy = "pk.book", cascade = CascadeType.ALL)
    	// @OneToMany(fetch = FetchType.LAZY, mappedBy = "pk", cascade =
    	// CascadeType.ALL)
    	public Set<Loan> getLoans() {
    		return loans;
    	}
     
    	public void setLoans(Set<Loan> loans) {
    		this.loans = loans;
    	}
     
    }
     
    @ApiModel(value = "Category Model")
    //@JsonIgnoreProperties(ignoreUnknown = true)
    @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 id")
    	private Integer id;
     
    	@ApiModelProperty(value = "Category code")
    	private String code;
     
    	@ApiModelProperty(value = "Category label")
    	private String label;
     
    	public String getCode() {
    		return code;
    	}
     
    	public void setCode(String code) {
    		this.code = code;
    	}
     
    	public String getLabel() {
    		return label;
    	}
     
    	public void setLabel(String label) {
    		this.label = label;
    	}
     
    	public Integer getId() {
    		return id;
    	}
     
    	public void setId(Integer id) {
    		this.id = id;
    	}
     
    	@Override
    	public int compareTo(CategoryDTO o) {
    		return label.compareToIgnoreCase(o.label);
    	}
    }
     
    @JsonIgnoreProperties(ignoreUnknown = true)
    @JsonDeserialize(using = BookDTODeserializer.class)
    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;
     
    	public Integer getId() {
    		return id;
    	}
     
    	public void setId(Integer id) {
    		this.id = id;
    	}
     
    	public String getTitle() {
    		return title;
    	}
     
    	public void setTitle(String title) {
    		this.title = title;
    	}
     
    	public String getIsbn() {
    		return isbn;
    	}
     
    	public void setIsbn(String isbn) {
    		this.isbn = isbn;
    	}
     
    	public LocalDate getReleaseDate() {
    		return releaseDate;
    	}
     
    	public void setReleaseDate(LocalDate releaseDate) {
    		this.releaseDate = releaseDate;
    	}
     
    	public LocalDate getRegisterDate() {
    		return registerDate;
    	}
     
    	public void setRegisterDate(LocalDate registerDate) {
    		this.registerDate = registerDate;
    	}
     
    	public Integer getTotalExamplaries() {
    		return totalExamplaries;
    	}
     
    	public void setTotalExamplaries(Integer totalExamplaries) {
    		this.totalExamplaries = totalExamplaries;
    	}
     
    	public String getAuthor() {
    		return author;
    	}
     
    	public void setAuthor(String author) {
    		this.author = author;
    	}
     
    	public CategoryDTO getCategory() {
    		return category;
    	}
     
    	public void setCategory(CategoryDTO category) {
    		this.category = category;
    	}
     
    	@Override
    	public int compareTo(BookDTO o) {
    		return title.compareToIgnoreCase(o.getTitle());
    	}
     
    	public BookDTO() {
    		super();
    	}
     
    	public BookDTO(String title, String isbn, LocalDate releaseDate, Integer totalExamplaries, String author,
    			CategoryDTO category) {
    		super();
    		this.title = title;
    		this.isbn = isbn;
    		this.releaseDate = releaseDate;
    		this.totalExamplaries = totalExamplaries;
    		this.author = author;
    		this.category = category;
    	}
     
    	/*
    	 * public BookDTO(String title, String isbn, Integer totalExamplaries, String
    	 * author, CategoryDTO category) { super(); this.title = title; this.isbn =
    	 * isbn; this.totalExamplaries = totalExamplaries; this.author = author;
    	 * this.category = category; }
    	 */
     
    }
     
    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();
    		JsonNode categoryCodeNode = node.at("/category/code");
    		System.out.println("categoryCodeNode : ");
    		System.out.print(categoryCodeNode);
    		String title = node.get("title").asText();
    		String isbn = node.get("isbn").asText();
    		String string = "2018-04-10T04:00:00.000Z"; // 2021-01-05T00:00:00.000Z
    		DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.ENGLISH);
    		LocalDate date = LocalDate.parse(string, formatter);
    		System.out.println("convertir date test : " + date);
    		/*
    		 * LocalDate releaseDate = LocalDate.parse(node.get("releaseDate").asText());
    		 * LocalDate registerDate = LocalDate.parse(node.get("registerDate").asText());
    		 */
    		LocalDate releaseDate = LocalDate.parse(node.get("releaseDate").asText(), formatter);
    		// LocalDate registerDate = LocalDate.parse(node.get("registerDate").asText(),
    		// formatter);
    		System.out.println("releaseDate  : " + releaseDate);
    		// System.out.println("registerDate : " + registerDate);
    		Integer totalExamplaries = (Integer) ((IntNode) node.get("totalExamplaries")).numberValue();
    		String author = node.get("author").asText();
    		// Category myCat = node.get("category")
    		// String codeCategory = node.get("code").asText();
    		String codeCategory = "M";
    		// String labelCategory = node.get("label").asText();
    		String labelCategory = "Mathematique";
     
    		return new BookDTO(title, isbn, releaseDate, 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 BookDTODeserializer() {
    		super(BookDTO.class);
    	}
     
    }
     
    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
    	}
     
    	public CategoryDTODeserializer() {
    		super(CategoryDTO.class);
    	}
     
    }
     
    Controller :
     
    @RestController
    @RequestMapping("/rest/book/api")
    @Api(value = "Book Rest Controller: contains all operations for managing books")
    public class BookRestController {
    	public static final Logger LOGGER = LoggerFactory.getLogger(BookRestController.class);
     
    	@Autowired
    	private BookServiceImpl bookService;
     
    	@GetMapping("/allbooks")
    	@ApiOperation(value = "List all book books of the Library", response = List.class)
    	@ApiResponses(value = { @ApiResponse(code = 200, message = "Ok: successfully listed"),
    			@ApiResponse(code = 204, message = "No Content: no result founded"), })
    	public ResponseEntity<List<BookDTO>> getAllBooks() {
    		List<Book> books = bookService.getAllBooks();
    		if (!CollectionUtils.isEmpty(books)) {
    			// on retire tous les élts null que peut contenir cette liste
    			books.removeAll(Collections.singleton(null));
    			List<BookDTO> bookDTOs = books.stream().map(book -> {
    				return mapBookToBookDTO(book);
    			}).collect(Collectors.toList());
    			return new ResponseEntity<List<BookDTO>>(bookDTOs, HttpStatus.OK);
    		}
    		return new ResponseEntity<List<BookDTO>>(HttpStatus.NO_CONTENT);
    	}
     
    	// @PostMapping("/addBook")
    	@RequestMapping(value = "/addBook", method = RequestMethod.POST, produces = "application/json", consumes = "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;
    	}
     
     
    	private Book mapBookDTOToBook(BookDTO bookDTO) {
    		ModelMapper mapper = new ModelMapper();
    		Book book = mapper.map(bookDTO, Book.class);
    		book.setCategory(new Category(bookDTO.getCategory().getCode(), ""));
    		book.setRegisterDate(LocalDate.now());
    		return book;
    	}
    }
    Aussi, j'ai une question, comment recuperer le Code et le label de la classe Category dans BookDTODeserializer ?

  4. #4
    Membre chevronné
    Homme Profil pro
    Ingénieur en génie logiciel
    Inscrit en
    Juin 2012
    Messages
    944
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Canada

    Informations professionnelles :
    Activité : Ingénieur en génie logiciel
    Secteur : High Tech - Opérateur de télécommunications

    Informations forums :
    Inscription : Juin 2012
    Messages : 944
    Par défaut
    Dans ta classe Book, pout la catégorie, tu devrais pas avoir de cascade... tu mets le cascades plutôt sur un one to many....

    Pour quelles raisons as-tu besoin de deserialisation?

  5. #5
    Membre confirmé
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Juin 2012
    Messages
    92
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Haute Garonne (Midi Pyrénées)

    Informations professionnelles :
    Activité : Développeur informatique
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Juin 2012
    Messages : 92
    Par défaut
    J'ai besoin de la serialisation, car sans cela, j'ai une erreur qui est mentionné dans la première partie de ma question.

Discussions similaires

  1. Réponses: 2
    Dernier message: 20/07/2015, 22h20
  2. [Python 2.X] Content-Type: text/html; charset=utf-8
    Par Mvu dans le forum Django
    Réponses: 1
    Dernier message: 08/09/2014, 16h35
  3. [Javamail] Lecture pièce jointe, content-type: Application/octet-stream
    Par rtsKyo dans le forum API standards et tierces
    Réponses: 1
    Dernier message: 20/06/2013, 17h56
  4. Réponses: 4
    Dernier message: 16/01/2013, 16h14
  5. Réponses: 5
    Dernier message: 26/11/2008, 10h06

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo