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

ou6hu8tu  于 2022-11-06  发布在  Java
关注(0)|答案(1)|浏览(165)

我的答复如下

[
    {
        "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"
            }
        ]
    }
]

我想将这个jsonMap到一个POJO对象,并且已经创建了这个类

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,但每个事件都是空值而不是Map。
有人能帮帮我吗?

ecr0jaav

ecr0jaav1#

要实现目标,必须按如下方式调整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"
            }
         }
      ]
   }
]

请注意已添加的 event 字段。
或者,更改您的DTO,如下所示:

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

相关问题