簡體   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