springboot接口入参与返回参数统一下划线格式

springboot接口入参与返回参数统一下划线格式,第1张

一、背景

java中命名规范是驼峰格式,而接口协议里入参和返回是下划线格式,需要在入参和返回时要进行格式转换。

二、传入参数--下划线转驼峰 1、get请求 1.1、@RequestParam注解方式

对应接收每个参数时,使用@RequestParam注解的value属性,对请求参数重命名。

@GetMapping("/detail")
public BaseReponse detail(@RequestParam(value="user_id") String userId) {
}
1.2、fastjson转换

使用对象接收参数时,获取参数map,然后使用fastjson转为目标对象(如:QueryObj)。

@GetMapping("/detail")
public BaseReponse detail(HttpServletRequest request) {
    // 获取参数map
    Map paramMap = ServletUtil.getParamMap(request);
    // 转为json字符串
    String jsonString = JSON.toJSONString(paramMap);
    // 转为java对象
    QueryObj query = JSON.parseObject(jsonString, QueryObj.class);
}

若QueryObj中有spring注解校验,无法在controller中使用@Valid注解,可在service中使用。

在service中使用@Valid注解

BaseResponse queryDetail(@Valid query);

 在serviceImpl中使用@Validated和@Valid注解

@Service
@Validated
public class TestServiceImpl implements TestService {
    
    @Override
    public BaseResponse queryDetail(@Valid QueryObj query) {
    } 
}
1.3、自定义注解,实现较复杂,略 2、post请求 2.1、使用@JsonNaming注解

post请求,controller中使用对象接收参数,并使用了@RequestBody,可使用@JsonNaming注解转换格式。

@Data
@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
public class QueryObj {
}

三、返回结果--驼峰转下划线 1、使用@JsonNaming注解

在返回结果ResponseVo上使用@JsonNaming注解,可自动将vo中属性转为下划线格式。

@Data
@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
public class ResponseVo {
}

缺陷:@JsonNaming只对当前对象(ResponseVo)生效,若ResponseVo中有内部类或引用其他对象,则需要对内部类或其他对象也使用@JsonNaming注解。

2、fastjson转换

使用fastjson设置序列化规则,对返回结果进行处理。

public static JSONObject transSnakeCase(Object obj) {
    SerializeConfig config = SerializeConfig.getGlobalInstance();
    // 设置为下划线格式
    config.setPropertyNamingStrategy(PropertyNamingStrategy.SnakeCase);
    // 设置显示值为null的属性
    String result = JSON.toJSONString(obj, config, SerializerFeature.WriteMapNullValue);
    return JSON.parseObject(result);
}

四、总结

使用fastjson提取公共的入参与返回方法,大多情况都可使用,入参或返回对象较简单时,可结合使用@RequestParam和@JsonNaming注解。

参考:springboot接口入参下划线转驼峰以及返回参数驼峰转下划线实现 - 李东平|一线码农 - 博客园

欢迎分享,转载请注明来源:内存溢出

原文地址:https://www.54852.com/langs/876792.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-13
下一篇2022-05-13

发表评论

登录后才能评论

评论列表(0条)

    保存