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
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With