账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    求教Springboot用Fastjson解析后,如何只应用于requestBody,返回对象还是用原来的?
    46
    0

    用了Fastjson,如何只让它处理请求报文,返回报文不处理,还是用SpringBoot原来的处理方式?

    添加Fastjson转换器的代码如下:

        @Bean
        public HttpMessageConverters fastJsonHttpMessageConverters() {
            // 创建FastJson配置
            FastJsonConfig fastJsonConfig = new FastJsonConfig();
            fastJsonConfig.setSerializerFeatures(SerializerFeature.WriteNullStringAsEmpty);
            
            // 创建converter消息转换对象
            FastJsonHttpMessageConverter4 fastJsonConverter = new FastJsonHttpMessageConverter4();
            fastJsonConverter.setFastJsonConfig(fastJsonConfig);
            
            return new HttpMessageConverters(fastJsonConverter);
        }

    以上代码在请求与返回都生效了,如何只让它在请求时生效,返回不处理?

    感谢各位!!

    0
    打赏
    收藏
    点击回答
        全部回答
    • 共 0 条
    • 放烟火的小笨蛋 普通会员 1楼

      在Spring Boot中,你可以使用@RequestBody注解来解析请求体。如果你只想将解析后的对象应用于请求体,你可以使用@RequestBody注解的@PostConstruct方法来初始化这个对象。

      以下是一个简单的例子:

      ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController;

      @RestController public class MyController {

      private MyService myService;
      
      @Autowired
      public MyController(MyService myService) {
          this.myService = myService;
      }
      
      @PostMapping("/myMethod")
      public MyObject myMethod(@RequestBody MyObject myObject) {
          return myService.myMethod(myObject);
      }
      

      } ```

      在这个例子中,@RequestBody注解告诉Spring Boot将解析请求体并将其应用于MyObject对象。@PostConstruct注解告诉Spring Boot在MyObject对象初始化完成后执行。

      请注意,@RequestBody注解只应用于POST请求。如果你使用的是PUT、PATCH或DELETE等其他请求方式,你可能需要使用不同的注解来解析请求体。

    更多回答
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部