ObjectMapper In Spring Controller Example

June 12, 2020 | No comments

Using ObjectMapper with Spring Boot Controller

If we are writing Spring Controller and want to get access to the request payload and convert it to the domain model. Then we have different ways of handling the request payload. For instance, we can use @RequestBody to convert the incoming payload to a domain object, or to a String, etc. In this article, we will see how we can use ObjectMapper to process incoming payload in s Spring Controller.
In this article, we will show a controller that accepts a JSON payload and then uses ObjectMapper to create instance of a domain object and then pass it to the service layer to persist it.

Example

BlogController with addBlogStory method.
Here we are reading the JSON input and converting it to a BlogStory Object. We are using ObjectMapper to convert the input JSON to a JsonNode object first. And then we are reading individual attributes from the JsonNode object and setting the corresponding field in our domain object.

@RestController
@RequestMapping("/blogapi")
public class BlogAPIController {
  private static final Logger log = LoggerFactory.getLogger(BlogAPIController.class);
  @Autowired
  BlogService blogService;

  @RequestMapping(value = {"/blogs"}, method = RequestMethod.POST,
      produces = MediaType.APPLICATION_JSON_VALUE)
  public Object addBlogStory(@RequestBody String input) {
    log.info("inside blog POST method" + input);
    ObjectMapper mapper = new ObjectMapper();
    BlogStory newStory = new BlogStory();
    try {
      JsonNode jsonNode = mapper.readTree(input);
      if (jsonNode.get("id") != null) {
        newStory.setId(jsonNode.get("id").asText());
      }
      if (jsonNode.get("name") != null) {
        newStory.setName(jsonNode.get("name").asText());
      }
      if (jsonNode.get("category") != null) {
        newStory.setCategory(jsonNode.get("category").asText());
      }
      else {
        newStory.setCategory("Finance");
      }
      if (jsonNode.get("summary") != null) {
        newStory.setSummary(jsonNode.get("summary").asText());
      }
      if (jsonNode.get("description") != null) {
        newStory.setDescription(jsonNode.get("description").asText());
      }

      blogService.addStory(newStory);
    } catch (Exception e) {
      log.error(e.getMessage());
    }

    ResponseEntity apiResponse = new ResponseEntity(newStory, HttpStatus.OK);
    return apiResponse;
  }

}
Notice that we have access to the JsonNode object, which we got from the mapper after reading the JSON payload. Now we can set custom logic. For instance if the category is null in the request payload we are setting default category "Finance"
Below is a sample JSON payload which will be acceptable by the above controller.
JSON Payload
{
    "id": "Java_15",
    "name": "Java 15",
    "summary": "Java 15 Blog Summary",
    "description": "Java 15 BlogLorem ipsum dolor sit amet, consectetur adipiscing elit",
    "category": "Technical"
}
Invoking the API
curl -X POST \
  http://localhost:8080/blogapi/blogs \
  -H 'Content-Type: application/json' \
  -d '{
    "id": "Java_15",
    "name": "Java 15",
    "summary": "Java 15 Blog Summary",
    "description": "Java 15 BlogLorem ipsum dolor sit amet, consectetur adipiscing elit",
    "category": "Technical"
}'
Please find the repository link and build instruction as follows.
Git Source Code
  • git clone https://github.com/siddharthagit/spring-boot-references
  • cd spring-rest
  • mvn clean install
  • mvn spring-boot:run

    Summary

    Using ObjectMapper to serialize JSON and then convert to a domain object gives more control. We then have access to the full JSON object and as we like we can populate the domain object after applying some transformation logic etc.

    References

    No comments :

    Post a Comment

    Please leave your message queries or suggetions.