繁体   English   中英

如何使用 ObjectMapper 将 String 转换为 java8 中的列表?

[英]How to convert String to list in java8 using ObjectMapper?

我有一个名为primarySkillStr的 JSON 字符串:

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

]

我尝试将它映射到一个对象,如下所示:

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

但是,当我将其转换为List时, roleIds List 为null 我做错了什么,还是有其他方法?

这是我的 DTO

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

我在PrimarySkillDTO类中有以下注释

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

问题是您的JsonNaming注释需要 snake_case 而您没有使用它。

解决它

  • 删除注释@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
  • 或者,将 JSON 字符串中的变量重命名为role_ids

SnakeCaseStrategy 将映射 roleIds <--> role_ids,以下代码对我有用:

ObjectMapper objectMapper = new ObjectMapper();

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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