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);
}
// 公共方法
public static T inputTransCamelCase(HttpServletRequest request, Class className) {
Map paramMap = ServletUtil.getParamMap(request);
String jsonString = JSON.toJSONString(paramMap);
return JSON.parseObject(jsonString, className);
}
若QueryObj中有spring注解校验,无法在controller中使用@Valid注解,可在service中使用。
在service中使用@Valid注解
BaseResponse detail(@Valid query);
在serviceImpl中使用@Validated和@Valid注解
@Service
@Validated
public class TestServiceImpl implements TestService {
@Override
public BaseResponse detail(@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);
}
// 返回BaseResponse
public class BaseResponse extends HashMap implements Serializeble {
private static final String DATA = "data";
public BaseResponse data (T data) {
this.put(DATA, data);
return this;
}
@Override
public BaseResponse put(String key, Object value) {
super.put(key, value);
return this;
}
}
// controller
@GetMapping("/detail")
public BaseReponse detail(HttpServletRequest request) {
return new BaseResponse<>(transSnakeCase(obj));
}
若要打印JSONObject,可打印jsonObject.entrySet(),默认的toString()方法,在SerializeFilterable中会过滤掉值为null的属性。
四、总结使用fastjson提取公共的入参与返回方法,大多情况都可使用,入参或返回对象较简单时,可结合使用@RequestParam和@JsonNaming注解。
参考:springboot接口入参下划线转驼峰以及返回参数驼峰转下划线实现 - 李东平|一线码农 - 博客园



