Search code examples
javajacksonjson-deserialization

Jackson deserialization list class


There is a json with a sheet as a nested class:

{
    "name": "test",
    "phoneList": {
        "phone": [
            {
                "number": 32323232,
                "code": 555
            },
            {
                "number": 4343423432,
                "code": 555
            }
        ]
    }
}

The following DTO class is suitable for this json:

class Response {

  String name;
  PhoneList phoneList;

  static class PhoneList {

    List<Phone> phone = new ArrayList<>();

    static class Phone {

      String number;
      Integer code;
    }
  }
}

Is it possible somehow not to create a PhoneList class, but to create a sheet directly?

class Response {

  String name;
  List<Phone> phoneList = new ArrayList<>();

  static class Phone {
    String number;
    Integer code;
  }
}

Solution

  • You may add below method and it is gonna work like a charm (of course if you make those DTOs proper Jacson pojos (i.e. default constructor + setters/getter)

    @JsonProperty("phoneList")
    private void mapPhones(Map<String, List<Phone>> phoneList) {
      this.phoneList = phoneList.get("phone");
    }