[ad_1]
Working from an existing API SDK and I’m trying to get rid of a large number of wrapper classes, which are there (mostly) to provide an object wrapper node.
eg: ProductRoot is a class, with a single property named product, of type Product (which is the actual class). As the API returns JSON that looks like this for a Product:
"product": {
"id": 632910392,
"title": "IPod Nano - 8GB",
....
I can remove the wrapper class ProductRoot, and instead annotate the Product class like this:
@JsonTypeName(value = "product")
@JsonTypeInfo(include = JsonTypeInfo.As.WRAPPER_OBJECT, use = JsonTypeInfo.Id.NAME)
And it works just fine.
HOWEVER, when the API is returning an array of products, it passes in JSON that looks like this:
{
"products": [
{
"id": 632910392,
"title": "IPod Nano - 8GB",
"body_html": "
Note the lack of a “product” node. So my code blows up with this error:
Caused by: com.fasterxml.jackson.databind.exc.InvalidTypeIdException: Could not resolve type id ‘id’ as a subtype of com.test.api.rest.model.Product: known type ids = [product] (for POJO property ‘products’)
at [Source: (org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$UnCloseableInputStream); line: 1, column: 15] (through reference chain: com.test.api.rest.model.ProductsRoot[“products”]->java.util.ArrayList[0])
Where ProductsRoot is a collection wrapper class, like so:
private List<Product> products = new LinkedList<Product>();
So I THINK the issue is that when it’s a single Product, I need the deserializer/serializer to wrap with a “product” node. However, when it’s an array/collection of products, I need each product to be unwrapped, or not wrapped.
So far I haven’t figured out how to do this using annotations or configuration. I think I could probably do it using a custom deserializer and custom serializer, but would need to do a fair bit of magic for it to work correctly, for all relevant types, etc… And I’m not sure that ends up being a lot better/clearer than the current wrapper class approach:(
Any suggestions or solutions? Thanks!
[ad_2]