(这个再确认下))
豆包生成下分分钟搞定直接拿来用。该工具支持互转实测好用。代码/* * 驼峰下划线转换工具类 */publicclassCamelSnakeUtils{privatestaticStringcamelToUnderline(StringcamelStr){if(camelStrnull||camelStr.isEmpty()){returncamelStr;}// 正则匹配大写字母替换为“_小写字母”PatternpatternPattern.compile([A-Z]);Matchermatcherpattern.matcher(camelStr);StringBuffersbnewStringBuffer();while(matcher.find()){matcher.appendReplacement(sb,_matcher.group().toLowerCase());}matcher.appendTail(sb);// 处理开头是大写的特殊情况如BuyerTaxNo → _buyer_tax_no → 去掉开头下划线if(sb.charAt(0)_){returnsb.substring(1);}returnsb.toString();}privatestaticJSONObjectprocessJsonObject(JSONObjectjsonObject){JSONObjectresultJsonnewJSONObject();// 遍历原JSON的每个Key-Valuefor(Map.EntryString,Objectentry:jsonObject.entrySet()){// Key转下划线StringnewKeycamelToUnderline(entry.getKey());// Value递归处理可能是对象/数组/基本类型ObjectnewValueprocessValue(entry.getValue());resultJson.put(newKey,newValue);}returnresultJson;}privatestaticJSONArrayprocessJsonArray(JSONArrayjsonArray){JSONArrayresultArraynewJSONArray();// 遍历数组每个元素for(Objectitem:jsonArray){// 元素递归处理resultArray.add(processValue(item));}returnresultArray;}privatestaticObjectprocessValue(Objectvalue){if(valueinstanceofJSONObject){// 是JSONObject调用processJsonObject处理returnprocessJsonObject((JSONObject)value);}elseif(valueinstanceofJSONArray){// 是JSONArray调用processJsonArray处理returnprocessJsonArray((JSONArray)value);}else{// 基本类型字符串、数字、布尔等直接返回returnvalue;}}publicstaticStringconvertCamelToUnderline(StringcamelJsonStr)throwsJSONException{if(camelJsonStrnull||camelJsonStr.isEmpty()){returncamelJsonStr;}// 先将JSON字符串解析为fastjson的Object可能是JSONObject/JSONArrayObjectjsonJSON.parse(camelJsonStr);if(jsoninstanceofJSONObject){returnprocessJsonObject((JSONObject)json).toJSONString();}elseif(jsoninstanceofJSONArray){returnprocessJsonArray((JSONArray)json).toJSONString();}else{// 既不是对象也不是数组如纯字符串/数字直接返回原内容returncamelJsonStr;}}}