Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jackson - Deserialize Array without property name

I have the following JSON response from shipcloud.io:

[
  {
    "name": "dhl",
    "display_name": "Deutsche Post DHL",
    "services": [
      "standard",
      "returns",
      "one_day",
      "one_day_early"
    ],
    "package_types": [
      "parcel",
      "bulk"
    ]
  },
  {
    "name": "dpag",
    "display_name": "Deutsche Post",
    "services": [
      "standard"
    ],
    "package_types": [
      "letter",
      "parcel_letter",
      "books"
    ]
  },
  {
    "name": "dpd",
    "display_name": "DPD - Dynamic Parcel Distribution",
    "services": [
      "standard",
      "returns",
      "one_day",
      "one_day_early"
    ],
    "package_types": [
      "parcel",
      "parcel_letter"
    ]
  }
]

How can I deserialize this JSON array with Jackson? Usually I use a simple POJO and define the property name of the list / array (@JsonProperty("blub") e.g.). Problem is, there is no property name used here... I tried it using an empty property name, but it didn't work. I'm just getting this error message:

Can not deserialize instance of Response.CarriersResponse out of 
START_ARRAY token
like image 693
Benjamin Reenk Avatar asked Apr 19 '17 13:04

Benjamin Reenk


2 Answers

If you want to use jackson, this is the solution that works for me:

ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, false);
like image 163
aUserHimself Avatar answered Nov 16 '22 08:11

aUserHimself


You are deserializing multiple objects of the type, so you need to do it as a list, like this

// somewhere in an example TypeReferences class
public static final TypeReference<List<Response.CarriersResponse>> CARRIER_RESPONSES = new TypeReference<List<Response.CarriersResponse>>() {
};

// elsewhere where you're calling the mapper
List<Response.CarriersResponse> responses = mapper.readValue(text, TypeReferences.CARRIER_RESPONSES);

You could instantiate it in-place, but that's a design decision between performance vs total memory consumption.

like image 1
coladict Avatar answered Nov 16 '22 08:11

coladict