简体   繁体   中英

Custom handler for response body in Jackson / Spring

I am trying to intercept the object that is being returned in my controller so that I can create a flat JSON structure of the response, before Spring invokes Jackson's serialization process.

I am going to support a query parameter that allows the client to flatten the response body. Something like:

/v1/rest/employees/{employeId}/id?flat=true

The controller method looks something like:

public Employee getEmployee(...) {}

I would like to avoid implementing this flattening logic in every one of my service calls and continue to return the Employee object.

Is there some kind of facility in Spring that would allow me to A) read the query string and B) intercept the object that is being returned as the response body?

Here's one idea. There may be a better way, but this will work:

Define an extra request mapping to do the flat mapping:

@RequestMapping(path = "/endpoint", params = {"flat"})
public String getFlatThing() {
    return flatMapper.writeValueAsString(getThing());
}

// The Jackson converter will do its ordinary serialization here.
@RequestMapping(path = "/endpoint")
public Thing getFlatThing() {
    return new Thing();
}

the "flatMapper" implementation can be whatever you like so long as it works. One option is to use Jackson's ObjectMapper to write the value as json first and then use https://github.com/wnameless/json-flattener to flatten that to your desired output. There may also be a way to define a custom ObjectMapper that does flat mapping, though that would take some more work on your part.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM