1

I have a POJO class which will be deserialized from JSON which comes as RequestBody in Spring. This POJO class contains List<String> as an instance variable. When this variable is deserialized, value is null. How to correctly deserialize it? Below are the code samples My POJO looks like below

@Getter
@AllArgsConstructor
@NoArgsConstructor
public class BookDto {
@JsonProperty("bookName")
private String bookName;
@JsonProperty("authors")
private List<String> authors;
@JsonProperty("description")
private String description;
}

My JSON object looks like below

{
 "bookName":"Vagrant Up and Running",
 "authors":["aone", "atwo"],
 "description":"Getting started guide for Vagrant development"
}

Below is the sample method call

public void method(@RequestBody BookDto bookDto) {}

I had followed given suggestion and the deserializer code is given below

public class AuthorDeserializer extends JsonDeserializer<List<String>> {
@Override
public List<String> deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
    Author author = jsonParser.readValueAs(Author.class);
    return author.authors;
}

private static class Author {
    public List<String> authors;
}
}
the_tech_maddy
  • 575
  • 2
  • 6
  • 21

2 Answers2

0

Make fields Public or add getter's to make them deserialize-able

Refer this for more deails

mc20
  • 1,145
  • 1
  • 10
  • 26
0

If you use Lombok, consider adding this annotation @Data like below:

@Data //You can remove the @Getter and @Setter annotation since @Data includes them
@NoArgsConstructor
public class BookDto {
   private String bookName;
   private List<String> authors;
   private String description;
}

Note: This is not related to the issue but please remove @JsonProperty()for clarity, this annotation is useless in your case since your JSON object's properties have the same name as your DTO's properties and by default the ObjectMapper use the names to map properties.

EDIT: @RequestBody deserializes the JSON for you so you don't need to do it manually.

akuma8
  • 4,160
  • 5
  • 46
  • 82