简体   繁体   中英

How to customize json response generated by Spring HttpMessageConverters

I am creating a rest webservice using spring @RestController and HttpMessageConverter.

It is working fine for simple scenario where my controller method is returning some POJO and spring converts it to JSON using "MappingJackson2HttpMessageConverter" as below:

{
     "firstName": "John",
     "lastName": "Smith",
 }

However properties name in JSON is same as the name of getters in my POJO. I want to modify the name of properties in my JSON dynamically.

Actually the requirement is to modify the JSON property names based on a logic. Eg if condition X then properties name in JSON should be as below:

{
     "fName": "John",
     "lName": "Smith",
 }

If Y then properties name in JSON output should be something else like:

{
     "MainName": "John",
     "SecondName": "Smith",
 }

So the property name cannot be tied to pojo and I also cannot use @jsonproperty as that would be compile time but i want to change at the runtime.

Is there a way to override MappingJackson2HttpMessageConverter and put my logic to decide json properties name there?

You can use @JsonAnySetter @JsonAnyGetter annotations. Behind you can use Map instance. In case you have always one-key-object you can use Collections.singletonMap in other case use HashMap or other implementation. Below example shows how easy you can use this approach:

public class User {

    private Map<String, String> values;

    @JsonAnySetter
    public void put(String key, String value) {
        values = Collections.singletonMap(key, value);
    }

    @JsonAnyGetter
    public Map<String, String> getValues() {
        return values;
    }

    @Override
    public String toString() {
        return values.toString();
    }
}

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