0

I sometimes get a single object and sometimes a list. Is there a way to handle the below 2 json messages using same Java models using Jackson library.

Message1: The below one has a list of "products"

{
  "id": 1234,
  "products": [
    {
      "producttype":"Household",
      "name": "product1",
      "price": 100
    },
    {
      "producttype":"Electronics",
      "name": "product2",
      "price": 200
    }
  ]
}

Message2: The below one has a single element under "products"

{
  "id": 1234,
  "products": {
      "producttype":"Household",
      "name": "product1",
      "price": 100
    }
}

I have the below Java models:

@JsonIgnoreProperties(ignoreUnknown = true)
public class Example
{
    private String id;
    private Products[] products;

    public String getId ()
    {
        return id;
    }

    public void setId (String id)
    {
        this.id = id;
    }

    public Products[] getProducts ()
    {
        return products;
    }

    public void setProducts (Products[] products)
    {
        this.products = products;
    }
}

But this fails when I try to convert it for Message2 since its a single object. ObjectMapper mapper = new ObjectMapper(); Example obj = mapper.readValue(originalMessage, Example.class);

Could you please help me handle the above scenario?

I am using the following libraries:

       <dependency>
          <groupId>org.codehaus.jackson</groupId>
          <artifactId>jackson-mapper-asl</artifactId>
          <version>1.9.13</version>
        </dependency>
        <dependency>
        <groupId>org.codehaus.jackson</groupId>
          <artifactId>jackson-jaxrs</artifactId>
          <version>1.9.13</version>
        </dependency>
        <dependency>
          <groupId>org.codehaus.jackson</groupId>
          <artifactId>jackson-xc</artifactId>
          <version>1.9.13</version>
</dependency>

Thanks!

  • You can do what you want, but you *really* should tell whomever is sending you Message2-format stuff to stop sending you bad data. They should be sending a list with a single element in it. – Darth Android May 04 '16 at 22:01

1 Answers1

0

You can use ACCEPT_SINGLE_VALUE_AS_ARRAY feature

ObjectMapper mapper = new ObjectMapper(); 
mapper.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
Example obj = mapper.readValue(originalMessage, Example.class);

https://fasterxml.github.io/jackson-databind/javadoc/2.7/com/fasterxml/jackson/databind/DeserializationFeature.html#ACCEPT_SINGLE_VALUE_AS_ARRAY

zafrost
  • 576
  • 3
  • 3