json字符串中key值下划线命名转换为驼峰命名:
例如:
原json串: String json= "{'user_name':'ok','user_sex':0,'object_info':{'business_code':'0001','business_info':{'business_name':'ok'}}}"; 转换为: String json= "{'userName':'ok','userSex':0,'objectInfo':{'businessCode':'0001','businessInfo':{'businessName':'ok'}}}";
具体工具类如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | public class JsonUtils { public final static void convert(Object json) { if (json instanceof JSONArray) { JSONArray arr = (JSONArray) json; for (Object obj : arr) { convert(obj); } } else if (json instanceof JSONObject) { JSONObject jo = (JSONObject) json; Set<String> keys = jo.keySet(); String[] array = keys.toArray( new String[keys.size()]); for (String key : array) { Object value = jo.get(key); String[] key_strs = key.split( "_" ); if (key_strs.length > 1 ) { StringBuilder sb = new StringBuilder(); for ( int i = 0 ; i < key_strs.length; i++) { String ks = key_strs[i]; if (! "" .equals(ks)) { if (i == 0 ) { sb.append(ks); } else { int c = ks.charAt( 0 ); if (c >= 97 && c <= 122 ) { int v = c - 32 ; sb.append(( char ) v); if (ks.length() > 1 ) { sb.append(ks.substring( 1 )); } } else { sb.append(ks); } } } } jo.remove(key); jo.put(sb.toString(), value); } convert(value); } } } public final static Object convert(String json) { Object obj = JSON.parse(json); convert(obj); return obj; } } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!