Points To Remember
Add the following dependency to the gradle project.compile('com.fasterxml.jackson.core:jackson-databind:2.7.1-1')
Read JSON in Filter and bind it to POJO class
You can read the JSON inside a Filter class in SpringBoot by
- Create a BufferedReader object by reading request object.
- Create an ObjectMapper object.
- Read JSON from bufferedReader object and bind it to any POJO class.
- package com.ekiras.test;
- import com.fasterxml.jackson.databind.JsonMappingException;
- import com.fasterxml.jackson.databind.ObjectMapper;
- import javax.servlet.*;
- import java.io.BufferedReader;
- import java.io.IOException;
- /**
- * @author ekansh
- * @since 26/3/16
- */
- public class MyFilter implements Filter {
- @Override
- public void init(FilterConfig filterConfig) throws ServletException {
- // some init code
- }
- @Override
- public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
- // declare a reader
- BufferedReader reader;
- try{
- // get reader from the request object
- reader = request.getReader();
- // create an object mapper instance
- ObjectMapper mapper = new ObjectMapper();
- // read values from the reader object and map the response to desired class.
- mapper.readValue(reader,Object.class);
- }catch (JsonMappingException e){
- e.printStackTrace();
- }
- }
- @Override
- public void destroy() {
- // some code to be run at destruction
- }
- }
So, in this way you can read JSON from the request and bind it to the any custom class.
Note :: To bind the JSON to any POJO class, you need to pass the class name of the pojo class to the objectMapper object.
e.g mapper.readValue(reader,MyCustomClass.class);
e.g mapper.readValue(reader,MyCustomClass.class);
Comments
Post a Comment