SpringBoot : Read JSON object from POST Request in Filter

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.
  1. package com.ekiras.test;  
  2.   
  3. import com.fasterxml.jackson.databind.JsonMappingException;  
  4. import com.fasterxml.jackson.databind.ObjectMapper;  
  5.   
  6. import javax.servlet.*;  
  7. import java.io.BufferedReader;  
  8. import java.io.IOException;  
  9.   
  10. /** 
  11.  * @author ekansh 
  12.  * @since 26/3/16 
  13.  */  
  14. public class MyFilter implements Filter {  
  15.   
  16.   
  17.     @Override  
  18.     public void init(FilterConfig filterConfig) throws ServletException {  
  19.         // some init code   
  20.     }  
  21.   
  22.     @Override  
  23.     public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {  
  24.         // declare a reader    
  25.         BufferedReader reader;  
  26.         try{  
  27.             // get reader from the request object  
  28.             reader = request.getReader();  
  29.             // create an object mapper instance  
  30.             ObjectMapper mapper = new ObjectMapper();  
  31.             // read values from the reader object and map the response to desired class.  
  32.             mapper.readValue(reader,Object.class);  
  33.         }catch (JsonMappingException e){  
  34.             e.printStackTrace();  
  35.         }  
  36.     }  
  37.   
  38.     @Override  
  39.     public void destroy() {  
  40.         // some code to be run at destruction  
  41.     }  
  42.   
  43. }  

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);

No comments :

Post a Comment