将 json 列表解析为对象列表 Java

Parse a json list into list of object Java

我的回复如下

[
    {
        "segmentId": "Source_2021-09-01_2021-10-01",
        "columns": [
            "merchantRefNum",
            "customerId",
            "firstName",
        ],
        "events": [
            {
                "merchantRefNum": "67456456",
                "customerId": rfgvkhbj,
                "firstName": "peter",
            },
            {
                "merchantRefNum": "654584856",
                "customerId": null,
                "firstName": "peter"
            }
        ]
    }
]

我想将这个 json 映射到一个 POJO 对象并创建了这个 class

public class MyClass {
  private String segmentId;
  private List<String> columns;
  private List<KeyValuePair> events;

  @Data
  @NoArgsConstructor
  @AllArgsConstructor
  @Builder
  @JsonIgnoreProperties(ignoreUnknown = true)
  public static class KeyValuePair {
    Map<String, String> event;
  }

}

我目前正在使用这种方式阅读这篇文章

List<MyClass> responses = new ObjectMapper().readValue(jsonString,new TypeReference<List<MyClass>>(){});

事件的大小为 2,但每个事件都以 null 而不是地图的形式出现。

有人可以帮我吗?

为了实现您的目标,您必须按如下方式调整您的 JSON:

[
   {
      "segmentId":"Source_2021-09-01_2021-10-01",
      "columns":[
         "merchantRefNum",
         "customerId",
         "firstName"
      ],
      "events":[
         {
            "event":{
               "merchantRefNum":"67456456",
               "customerId":"rfgvkhbj",
               "firstName":"peter"
            }
         },
         {
            "event":{
               "merchantRefNum":"654584856",
               "customerId":null,
               "firstName":"peter"
            }
         }
      ]
   }
] 

注意已添加的事件字段。

或者,像这样更改您的 DTO:

class MyClass {
        private String segmentId;
        private List<String> columns;
        private List<Map<String, String>> events;
    }