如何为 Spring 动态实现 ObjectMapper
客户端可以通过将 PropertyNamingStrategy 添加到 api 参数来决定它是 SNAKE_CASE 还是 CAMEL_CASE。
我的想法是在进入控制器之前做aop拦截器来定制ObjectMapper。
我为 ObjectMapper 对象设置了 setPropertyNamingStrategy,但它只获得第一个 PropertyNamingStrategy 设置,不使用第一次之后设置的值。
@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);
}
}
}
谢谢
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您应该阅读 ObjectMapper< 的 JavaDoc /a>.
您所看到的是预期行为,如 JavaDoc 中所述:配置只能在首次读/写使用之前完成。首次使用后,更改配置可能无效或可能导致错误。 JavaDoc 还解释了如何解决该限制。
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.