0

Is there an easy way to have request params names different than the field names in the class used as @ParameterObject?

The reason I want to use different name is that the request parameters are expected to contain an underscore and it's not something I would like to have in a field or method name, so I'm looking for solutions that don't require this.

Below an example of what I would like to achieve.

Parameter object:

public class SearchParams {

    private String someParam;
    private String someOtherParam;

}

In controller:

@GetMapping
public SomeResponse getFoos(@ParameterObject SearchParams params) {
    return fooService.getFoos(params);
}

Request path:

GET /foos?some_param=abc&some_other_param=xyz
Chanandler Bong
  • 403
  • 1
  • 11
  • 23

1 Answers1

1

You can achieve this with additional getter/setter pair. Like here:

public class SearchParams {
    private String someName;

    public String getSomeName() {
        return someName;
    }

    public void setSomeName(String someName) {
        this.someName = someName;
    }
    public String getSomeDifferentName() {
        return someName;
    }

    public void setSomeDifferentName(String someName) {
        this.someName = someName;
    }
}
Mar-Z
  • 2,660
  • 2
  • 4
  • 16
  • Thanks. This works, so +1. However it's not something I would like to use. The reason I want to use different name is that the parameter is expected to contain an underscore and it's not something I would like to have in a field name or (in case of your solution) method name. I'll update my question to make it clear. – Chanandler Bong Jun 20 '23 at 13:35
  • With JSON request body instead of URL parameters it would be much easier. – Mar-Z Jun 20 '23 at 18:36