简体   繁体   中英

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)

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

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM