Search code examples
javajsonjersey

Retrieving Java Objects from a json post request


I am developing a restful web application using java and jax-rs. In server side, I have to accept Json type requests as given by the client using POST method.

@POST
@Path("/Request")
@Consumes(MediaType.APPLICATION_JSON)
public String process(SMessage message) throws Exception  {
         message.getHeader();
         message.getBody();
}

The json object have two composite fields like in the below format.

{
  "header": {
    "serviceType": "A"
  },
  "body": {
    "id": "1",
    "name": "abc"
  }
}

Based on the serviceType specified in the Header field, the parameters in the body will differ. I need to map this body field in to a java POJO class. The POJO class is not the same for all requests. How can I achieve this effectively?


Solution

  • If you are using Jackson as your JSON parser, a simple way is to declare body to be a JsonNode to handle dynamic keys as follows:

    class MyResponse {
        private MyHeader header;
        private JsonNode body;
    
        //general getters and setters
    }
    

    And I assumed that you have already a POJO for header such as:

    class MyHeader {
        private String serviceType;
    
        //general getters and setters
    }
    

    Finally, let's verify that it works:

    String responseStr = "{\"header\": {\"serviceType\": \"A\"},\"body\": {\"id\": \"1\",\"name\": \"abc\"}}";
    
    ObjectMapper mapper = new ObjectMapper();
    MyResponse myResponse = mapper.readValue(responseStr, MyResponse.class);
    System.out.println(myResponse.getBody().get("name").asText());
    

    Console output:

    abc

    Another way to solve this issue is by using Map and everything else is the same:

    class MyResponse {
        private MyHeader header;
        private Map<String, Object> body;
    
        //general getters and setters
    }