javajsonspring-bootmavenjsonparser

Json Parsing and assign to DTO


Issue while parsing JSON into DTO.

JSON response is :

{
  "content": [
    {
      "id": 350,
      "reg": "FA-2001",
      "Email": "abc@gmail.in",
      "Mobile": "+9192000000",
      "Name": "dr kumar",
      "Ip": "0:0:0:0:0:0:0:1",
      "Datetime": "2022-10-20T13:50:49",
    }
  ],
  "pageable": {
    "sort": {
      "unsorted": false,
      "sorted": true,
      "empty": false
    },
    "pageNumber": 0,
    "pageSize": 20,
    "offset": 0,
    "paged": true,
    "unpaged": false
  },
  "last": true,
  "totalPages": 1,
  "totalElements": 1,
  "first": true,
  "sort": {
    "unsorted": false,
    "sorted": true,
    "empty": false
  },
  "numberOfElements": 1,
  "size": 20,
  "number": 0,
  "empty": false
}

DTO

@Data
public class OtherResponse {
    @JsonProperty(value = "content")
    private Map content;
}

Getting

com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize value of type java.util.LinkedHashMap<java.lang.Object,java.lang.Object> from Array value (token JsonToken.START_ARRAY)

Please suggest how to get value in Map or some other object My main focus is to send specific key value pair in response.


Solution

  • In your json String, the content is a List. what you can do is to update the OtherResponse accordingly:

    @Data
    public class OtherResponse {
        @JsonProperty(value = "content")
        private List<Map<String, String>> content;
    
        private Pageable pageable;
    }
    

    Or even define a dedicated class for it:

    @Data
    public class OtherResponse {
        @JsonProperty(value = "content")
        private List<Person> content;
    
        private Pageable pageable;
    }
    

    PS: updated answer and added the Pageable field. I am using here the Pageable interface imported from org.springframework.data.domain.Pageable