简体   繁体   中英

Jackson JSON deserialization

I am trying to deserialize the following Json payload using Jackson:

[{
  "owner" : "345MWyh7w4hY98W6",
  "url" : "http://www.google.com",
  "items" : [{
    "createdAt" : 1342099411415,
    "amount" : 1,
    "note" : "item 1",
    "product" : "car"
  }, {
    "createdAt" : 1342100231111,
    "amount" : 4,
    "note" : "item 2",
    "product" : "wheels"
  }],
  "createdAt" : 1342096943777,
  "title" : "Car order",
  "description" : "car order",
  "id" : "98hw85Y945e6U358"
}]

I am using the following code to deserialize:

ObjectMapper mapper = new ObjectMapper().configure(
        DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

List<Order> result = null;
try {
    result = mapper.readValue(jsonString,new TypeReference<List<Order>>() { });
} catch (IOException e) {
    e.printStackTrace();
}

However I get the following error:

org.glassfish.jersey.message.internal.WriterInterceptorExecutor$TerminalWriterInterceptor aroundWriteTo
SEVERE: MessageBodyWriter not found for media type=application/json, type=class org.glassfish.jersey.client.InboundJaxrsResponse, genericTyp
e=class org.glassfish.jersey.client.InboundJaxrsResponse.
Feb 06, 2015 8:14:45 PM org.glassfish.jersey.filter.LoggingFilter log

The class Orders is generated by RAML -> JAX-RS maven plug-in and this does not have a zero argument constructor. Is there any way of doing this de-serialization other than modifying the generated class to add a zero-args constructor ?

Was able to fix with a work-around. I created a wrapper DTO over the Order as follows:

@XmlRootElement
public class OrderDTO {

    private List<Order> orderList;

    public List<Order> getOrderList() {
        return orderList;
    }

    public void setOrderList(List<Order> orderList) {
        this.orderList = orderList;
    }

    public void addOrder(Order order){
        orderList.add(order);
    }

    public OrderDTO() {
        super();
        orderList = new ArrayList<Order>();
    }
}

here I was able to add the zero-args constructor. Now it works :).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM