Store request body as JSON into the database – Java

I want to store the request body into the database. I am storing the headers and request into the audit trail table.

For conversion of headers, I am creating a map and then storing the json into the database like this:

        String method = httpServletRequest.getMethod();
        Enumeration<String> values = httpServletRequest.getHeaderNames();
        Map<String,String> headers = new HashMap<String, String>();

        while (values.hasMoreElements()) {
            String key = values.nextElement();
            String innerValue = (String)httpServletRequest.getHeader(key);
            headers.put(key,innerValue);
        }

       // converting object to Array
       auditTrail.setHeaders(appUtility.objectToString(headers));

How can I store the request body as json into the database (ignore files for now)? The request body can be one object, array of objects or a combination.

Right now, I have written an ASPECT which will store all the incoming requests into the database. It’s easy to store the json of the object when I know the Object but how can we make it generic?

Answer

If you know that content is JSON and want to read data from stream you can do it on this way:

String jsonBody = request.getReader().lines()
   .collect(Collectors.joining(System.lineSeparator()));

If you need to validate is jsonBody really JSON you can use Jackson:

public static boolean isJSONValid(String jsonInString ) {
 try {
     final ObjectMapper mapper = new ObjectMapper();
     mapper.readTree(jsonInString);
     return true;
  } catch (IOException e) {
     return false;
  }
}

If you have a body as the object you can use Jackson.

Example:

SomeObject body = ...; // Your body
ObjectMapper objectMapper = new ObjectMapper();
String bodyAsString = objectMapper.writeValueAsString(body); // To JSON
body = objectMapper.readValue(bodyAsString, SomeObject.class); // From JSON

Jakson with maven:

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
</dependency>