Skip to content
Advertisement

Parse a json list into list of object Java

I have a response as follows

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

I want to map this json to a POJO object and have created this 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;
  }

}

I am currently using this way to read this

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

The size of events is 2 but each event is coming as null instead of a map.

Can Someone please help me ?

Advertisement

Answer

To achieve your goal you have to adjust your JSON as follows:

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

Notice the event fields that have been added.

Or, change your DTO, like this:

class MyClass {
        private String segmentId;
        private List<String> columns;
        private List<Map<String, String>> events;
    }
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement