如何为 Spring 动态实现 ObjectMapper

发布于 2025-01-12 00:22:38 字数 1073 浏览 2 评论 0原文

客户端可以通过将 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

你的背包 2025-01-19 00:22:38

您应该阅读 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文