Handling the Json response in Spring MVC after the initial processing

I have a range of controllers that utilize the @ResponseBody annotation to return a common Response object:

@RequestMapping(value = "/status", method = RequestMethod.GET)
    @Transactional(readOnly = true)
    public @ResponseBody Response<StatusVM> status()

After the Response is returned, I need to perform a specific operation on each controller. This operation will enhance the Response object by adding new data.

In order to avoid duplicating code, I am searching for a centralized intervention point. Initially, I considered using Interceptors, but according to the documentation http://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-handlermapping-interceptor, it does not function effectively with @ResponseBody:

Take note that the postHandle method of HandlerInterceptor may not be ideally suited for use with @ResponseBody and ResponseEntity methods. In such scenarios, an HttpMessageConverter writes to and commits the response before postHandle is called, rendering it impossible to modify the response (e.g., add a header). Instead, an application can implement ResponseBodyAdvice and either declare it as an @ControllerAdvice bean or configure it directly on RequestMappingHandlerAdapter.

Although I have been unable to locate an example of this technique, any assistance would be greatly appreciated.

An alternative approach could involve utilizing aspects, but this would require annotating each individual controller, which I would prefer to avoid.

Answer №1

Implemented the ResponseBodyAdvice as follows:

@ControllerAdvice
public class StatusAdvice implements ResponseBodyAdvice<Response<?>> {

    @Override
    public boolean supports(MethodParameter returnType,
            Class<? extends HttpMessageConverter<?>> converterType) {
        if (returnTypeIsJson(returnType)&&responseConverterIsJackson2(converterType)){
            return true;
        }
        return false;
    }

....

    @Override
    public Response<?> beforeBodyWrite(Response<?> body, MethodParameter returnType,
            MediaType selectedContentType,
            Class<? extends HttpMessageConverter<?>> selectedConverterType,
            ServerHttpRequest request, ServerHttpResponse response) {
        ....

        return body;
    }

}

So it turned out to be simpler than initially anticipated.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilize JSON data to dynamically populate TextFields or Select menus depending on a specific key in the JSON object

As I retrieve multiple JSON groups from an API, each group contains one or more questions objects. The task at hand is to attach each question along with its corresponding response to a textField. Based on the value of QuestionType, it will be decided whet ...

Order JSON array based on the time, extract the pairs of keys and values, and transfer them to a Google

My goal is to extract the most recent entry from a JSON array stored in a Google Sheet and copy it into two adjacent columns. The desired data resides in Column L of my spreadsheet (starting from row 2) and follows this format: [{"id": "XX:123456", "time ...

Utilize Python to consolidate data from various API requests

I am currently developing an application that will need to interact with multiple external APIs to gather information and then present the results to a client. The client interacts with the application through a web interface, submitting queries to the ser ...

What methods can be used to carry out personalized deserialization for specific fields?

I'm working on extracting data from my Firefox bookmarks for further manipulation. To my surprise, the process went smoothly with the following code: class Bookmark { public string title; public int? id; public int? parent; public str ...

Is there a way to convert a flat JSON into several instances of a sub-class through deserialization?

Here is a flat JSON string that needs to be deserialized in Java using Jackson: {"ccy":"EUR", "value1":500, "value2":200, "date":"2017-07-25", "type":"", ... <many other pairs>} To deserialize this JSON string, we can create the following ...

"JSON data is successfully obtained through Ajax Request but triggers an error in

After conducting a thorough search for the error, I came across some useful hints which unfortunately did not help in resolving the issue. Many of the queries raised were related to an invalid JSON response. The problem arises when making an Ajax request ...

Best method for transferring Entity details to a jquery dialog box within ASP.NET MVC 3

I am currently working on an ASP.NET MVC 3 Page where I need to loop through a collection of objects in the Model. Each object will have a button next to its information for users to edit it in a jQuery UI dialog. However, I am facing a dilemma in finding ...

The openweathermap API contains a section enclosed in square brackets, preventing the retrieval of JSON data in Android Studio

Currently, I am in the process of developing a weather application. The API seems to be functioning properly but only in specific locations. At this stage, my main focus is on creating a Toast message using the API to verify its functionality before procee ...

A guide on adding a JSON object to an array in R

I have attempted various methods to insert a JSON object into an array and save it in the same format as the example below, but unfortunately, I have not been successful. Does anyone have a solution to accomplish this in R? Thank you EDIT : I have foun ...

extract objects from an array of objects based on a specified array

Within my JSON array, I have data structured like this: const data = [ { "uniqueId": 1233, "serviceTags": [ { "Id": 11602, "tagId": "FRRRR", "missingRequired&quo ...

Finding the measurement of a sofa using couch.get(data, headers, status)

After attempting to set up a node.js application with express.js by connecting to couchdb, I utilized the npm package called nodejs-couch. app.get('/', function(req, res) { couch .get(dbName, viewUrl) .then( function(data, heade ...

Having trouble pinpointing the source of the error and finding a solution

*While attempting to parse some data through JSON, I encountered an issue where clicking on a specific button caused the parsing activity to stop working. The rest of the app is functioning properly except for this particular button.* Main Activity Button ...

What is the best method for saving a JSON resource on my device?

When I make a JSON request, it provides me with various parameters, one of which is the name. I want to create a variable to cache this name parameter so that I can access it later in my app. For instance, if the name from JSON request is "david", I would ...

Moving the query function from routes to the repository in Laravel

Greetings! I am relatively new to the world of Laravel and I am in the process of setting up a repository to consolidate repeated database calls. It seemed logical to centralize these calls for easier reference. Currently, I have a chained select feature t ...

Guide on indicating a non-mandatory component within a JSON request entity

When working on an API blueprint, I am interested in defining a JSON element as optional for a POST request. Here is an example: ### Add a new User [POST] To add a User, send a JSON object .... + Request (application/json) { "na ...

Refresh a div on an ASP MVC page with a controller action without the need to reload the entire page

In my controller, I have implemented the following action: public ActionResult TestItemLogistic() { ControlViewModel model = new ControlViewModel(); model.itemSelected = "Logistic"; return RedirectToAction("MenuList", model); ...

Error message encountered "HttpMessageNotReadableException" during JSON request conversion in Python

I've encountered an issue with a REST API request in JSON format that I am unable to convert. The code for the request is as follows: headers = {"content-type": "application/json","username": "xxx" , "password": "xxx" , "domain": "xxx" } r = request ...

Utilize jQuery to extract data from a JSON object

While I have come across numerous examples of parsing JSON objects in jQuery using $.parseJSON and have grasped the concept, there are some fundamental aspects missing that are preventing me from successfully parsing the following VALID JSON: { "studen ...

Using an ArrayList to display a RecyclerView Adapter populated with JSON data

I'm currently working on developing an Adapter for a RecyclerView that is being displayed using an ArrayList. However, I have a question regarding the public RecyclerViewHolder located at the bottom of the code. Should I include the ArrayList in it, o ...

Encountering issues after setting up JSON API in Swift

I have successfully implemented most of the functionality. However, when I build the project and execute the function, it processes the API content before crashing abruptly. Here is the updated code snippet: // // GamesTableViewController.swift // Footb ...