I'm using Jackson
to deserialize a response from a restful call to the ups api
for shipment tracking information.
In the response, if there's more than one package per shipment I get a response similar to the following snippet
"Shipment": {
"InquiryNumber": {
"Code": "01",
"Description": "ShipmentIdentificationNumber",
"Value": "some-value-here"
},
"ShipperNumber": "1234",
"Package": [{
"TrackingNumber": "12345"
},
{
"TrackingNumber": "67890"
}
]
}
}
This is fine and I can un-marshall this using Jackson simply enough with the following:
@JsonDeserialize(builder = Shipment.Builder.class)
@Builder(builderClassName = "Builder")
@Getter
public class Shipment {
@JsonProperty("ShipperNumber")
private final String shipperNumber;
@JsonProperty("Package")
private final List<Package> packages;
@JsonPOJOBuilder(withPrefix = "")
public static class Builder {
}
}
However, if there is only one package
item in the api response, then rather than return it as a collection of packages with one entry, it returns it as a single object such as below:
"Shipment": {
"InquiryNumber": {
"Code": "01",
"Description": "ShipmentIdentificationNumber",
"Value": "some-value-here"
},
"ShipperNumber": "1234",
"Package": {
"TrackingNumber": "12345"
}
}
}
This throws the below error, because Jackson isn't able to deserialize the object into a list (obviously)
JSON parse error: Cannot deserialize instance of
java.util.ArrayList<com.example.Package>
out of START_OBJECT token;
Is there a way for Jackson to marshall the data depending on the datatype ie collection or single object?