Supriya C S
Supriya C S

Reputation: 133

How to convert String to list in java8 using ObjectMapper?

I have a JSON String called primarySkillStr :

[
  {
    "id": 3,
    "roleIds": [
      2
    ],
    "rating": 2
  }

]

I try to map it to an object as follows:

primarySkillList = mapper.readValue(primarySkillStr, 
    new TypeReference<List<PrimarySkillDTO>>() {});

But when Iam converting this to a List then the roleIds List is null. Am I doing something wrong, or is there any other way?

This is my DTO

public class PrimarySkillDTO {
    private Integer id;
    private Integer rating;
    private List<Integer> roleIds;
    private String name;
}

I have the following annotations in the PrimarySkillDTO class

@Data
@Builder
@AllArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)

Upvotes: 2

Views: 3294

Answers (2)

Vikki
Vikki

Reputation: 2025

SnakeCaseStrategy will map roleIds <--> role_ids, The following codes work for me:

ObjectMapper objectMapper = new ObjectMapper();

TypeReference<List<TestClass>> typeRef = new TypeReference<List<TestClass>>() {};

List<TestClass> testList = objectMapper.readValue(testStringObject, typeRef);

Upvotes: 3

Nick Vanderhoven
Nick Vanderhoven

Reputation: 3093

The problem is that your JsonNaming annotation requires snake_case and you are not using it.

To solve it

  • remove the annotation @JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
  • or, rename the variable in the JSON String to role_ids

Upvotes: 5

Related Questions