The client can decide whether the PropertyNamingStrategy is SNAKE_CASE or CAMEL_CASE by adding it to the api parameter.
my idea is to do aop interceptor before entering the controller to customize ObjectMapper.
I have setPropertyNamingStrategy for ObjectMapper object but it only get first PropertyNamingStrategy set, values set after first time are not used.
@Aspect
@Component
@RequiredArgsConstructor
public class NamingJsonAspect {
private final ObjectMapper objectMapper;
@Pointcut("execution(public * com.nnv98..*Controller.*(..))")
private void namingJson() {}
@SneakyThrows
@Before("namingJson()")
public void doAround(JoinPoint proceedingJoinPoint) {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
assert attributes != null;
HttpServletRequest request = attributes.getRequest();
String namingJson = request.getParameter("namingJson");
if(namingJson.equals("SNAKE_CASE")){
objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
}else {
objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.LOWER_CAMEL_CASE);
}
}
}
thank you
CodePudding user response:
You should read the JavaDoc for ObjectMapper.
What you are seeing is expected behavior, as explained in the JavaDoc: configuration can only be done before first read/write usage. After first usage, changing the configuration may have no effect or may result in errors. The JavaDoc also explains how you can work around the limitation.