I am creating a service that receives requests as JSON messages. I need to parse the message and take appropriate action based on the type of request. For example (in pseudo-code):
switch(request.type) { case "NewOrder": createNewOrder(order); break; case "CancelOrder" cancelOrder(orderId); break; }
It looks like most JSON APIs (at least the ones that perform object matching for you) need a root object type to deserialize. Is there an elegant way around this?
As an example, in the Jackson API (using full object mapping) I need to call mapper as follows:
NewOrder newOrder = mapper.readValue(src, NewOrder.class); CancelOrder cancelOrder = mapper.readValue(src. CancelOrder.class);
This means that I need to know the class of the object before I even parsed it. I really need some way to look into the JSON string, determine the type of request, and then call the appropriate readValue () method - something like this:
String requestType = getRequestType(src); switch(request.type) { case "NewOrder": NewOrder newOrder = mapper.readValue(src, NewOrder.class); createNewOrder(newOrder.order); break; case "CancelOrder" CancelOrder cancelOrder = mapper.readValue(src. CancelOrder.class); cancelOrder(cancelOrder.orderId); break; }
Can this be done using Jackson or any other Java JSON parser? I am sure that I can go to a lower level and use the streaming API or the node interface API, but try to avoid this complexity if I can.
source share