前言

有时候通过Feign会接收到老系统发来的实体类,和数据库保持一致,都是下划线的属性名,而你需要驼峰映射,你拿到的只是原始数据,网上很多办法,取字段转换属性名,利用注解映射,或者设置工具类之类的,我觉得都比较麻烦,上手程度慢,所以使用了一种简单方式,JSON转换!可以直接自动驼峰映射

案例

Before conversion

{   
"customer_number": "1017",
"customer_name": "盐山阜德医院",
"customer_id": 1057,
"status": "A",
"tax_reference": null,
"tax_code": "16%专用",
"customer_type": "I",
"customer_type_meaning": "增值税普通发票",
"customer_class_code": "医院",
"class_code_meaning": "医院"
}

After conversion

{   
"customerNumber": "1017",
"customerName": "盐山阜德医院",
"customerId": 1057,
"status": "A",
"taxReference": null,
"taxCode": "16%专用",
"customerType": "I",
"customerTypeMeaning": "增值税普通发票",
"customerClassCode": "医院",
"classCodeMeaning": "医院"
}

1、转对象

//转换为指定对象 驼峰映射阿里解决了 直接映射实体类即可
List<ErpCustomerVo> erpCustomerVos = JSON.parseArray(items1, ErpCustomerVo.class);
public PageResponse<ErpCustomerVo> getErpCustomer(Map param) {
//获取响应数据 数据源 或者你的下划线对象
ResponseVo erpCustomer = erpClient.getErpCustomer(param);
//封装map
HashMap<String,Object> hashMap=( HashMap<String,Object> )erpCustomer.getData();
//转为json 用阿里巴巴的JSON
String s = JSON.toJSONString(hashMap);
//封装分页 这个你不用的话不用管
DataVo data = JSON.parseObject(s,DataVo.class);
//获取data数据层 items 看你获取的数据实体类这一层用的什么封装了
String items1 = JSON.toJSONString(hashMap.get("items"));
//转换为指定对象 驼峰映射阿里解决了
List<ErpCustomerVo> erpCustomerVos = JSON.parseArray(items1, ErpCustomerVo.class);
//分页返回 不用的话不写
PageResponse<ErpCustomerVo> erpCustomerVoPage =new PageResponse<>();
erpCustomerVoPage.setTotal(data.getCount());
erpCustomerVoPage.setPageSize(data.getLimit());
erpCustomerVoPage.setRecords(erpCustomerVos);

return erpCustomerVoPage;
}

2、字符串转驼峰互转

public static void main(String[] args) {
//helloJsGo
System.out.println(StringUtils.toCamelCase("hello_js_go"));
//hello_js_go
System.out.println(StringUtils.toUnderScoreCase("helloJsGo"));
}

拓展

Object转JSON字符串:
String jsonStr = JSONObject.toJSONString(object);

JSON字符串转JSONObject:
JSONObject jsonObject = JSONObjcet.parseObject(jsonStr);

JSON字符串转Object对象
T t = JSON.parseObject(jsonStr,T.class);

祝你幸福

送你一首歌 《Light of the Seven》美剧《权力的游戏 第六季》原声​​

附图:苏州•甪直 叶圣陶纪念馆 2018-7-27 10:00:44

字符串下划线驼峰映射实体类参数json对象_下划线转驼峰