Search code examples
jsondeserializationresttemplate

How to deserialize JSON with RestTemplate when the request body is either a list or an object?


I am trying to deserialize JSON from consuming an API. However the JSON body coming from the API is not consistent. Sometimes it comes as a list, and sometimes as a single item.

Example:

"Charge": [
            {
              "ChargeType": "EXPRESS 12:00",
              "ChargeAmount": 0.0
            },
            {
              "ChargeCode": "YK",
              "ChargeType": "12:00 PREMIUM",
              "ChargeAmount": 0.0
            },
          ]

And in another case:

"Charge": {
            "ChargeType": "EXPRESS",
            "ChargeAmount": 8.5
          }

I am using RestTemplate and DTOs.

My DTO is built like this.

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class Charges {

    @JsonProperty(value = "Currency")
    private String currency;

    @JsonProperty(value = "Charge")
    private List<Charge> charges;
}

This fails on the case when it comes as an object:

com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `java.util.ArrayList<Charge>` out of START_OBJECT token

Is there a way I can solve this without creating my Custom JSON Converter? And if I have to create it, how can I do it?


Solution

  • Solved by using:

     @JsonProperty(value = "Charge")
     @JsonFormat(with = JsonFormat.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY)
     private List<Charge> charges;