根据使用jackson的类型从JSON解析对象

时间:2016-05-04 21:55:37

标签: java json jackson

我有时会得到一个对象,有时候会得到一个列表。有没有办法使用Jackson库使用相同的Java模型处理以下2个json消息。

Message1:下面有一个“产品”列表

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

Message2:下面的一个元素在“products”下有一个元素

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

我有以下Java模型:

@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;
    }
}

但是,当我尝试将其转换为Message2时,由于它是单个对象,因此失败了。     ObjectMapper mapper = new ObjectMapper();             示例obj = mapper.readValue(originalMessage,Example.class);

你能帮我处理上面的情况吗?

我正在使用以下库:

       <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>

谢谢!

1 个答案:

答案 0 :(得分:0)

您可以使用ACCEPT_SINGLE_VALUE_AS_ARRAY功能

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