zoukankan      html  css  js  c++  java
  • 对json数据key进行替换

    原文:https://blog.csdn.net/qq_39750658/article/details/83411897

    import java.util.HashMap;
    import java.util.Map;
    import java.util.Set;
    
    import com.alibaba.fastjson.JSONArray;
    import com.alibaba.fastjson.JSONObject;
    
    /**
     * 
     * 对json数据key进行替换
     */
    public class JSONUtil {
    
        public static JSONObject changeJsonObj(JSONObject jsonObj,Map<String, String> keyMap) {
            JSONObject resJson = new JSONObject();
            Set<String> keySet = jsonObj.keySet();
            for (String key : keySet) {
                String resKey = keyMap.get(key) == null ? key : keyMap.get(key);
                try {
                    JSONObject jsonobj1 = jsonObj.getJSONObject(key);
                    resJson.put(resKey, changeJsonObj(jsonobj1, keyMap));
                } catch (Exception e) {
                    try {
                        JSONArray jsonArr = jsonObj.getJSONArray(key);
                        resJson.put(resKey, changeJsonArr(jsonArr, keyMap));
                    } catch (Exception x) {
                        resJson.put(resKey, jsonObj.get(key));
                    }
                }
            }
            return resJson;
        }
        
        public static JSONArray changeJsonArr(JSONArray jsonArr,Map<String, String> keyMap) {
            JSONArray resJson = new JSONArray();
            for (int i = 0; i < jsonArr.size(); i++) {
                JSONObject jsonObj = jsonArr.getJSONObject(i);
                resJson.add(changeJsonObj(jsonObj, keyMap));
            }
            return resJson;
        }
        
        public static void main(String[] args) {
            String jsonStr = "{"user":{"name":"张三","sex":"男","hobby":[{"motion":"足球","desc":"任性"},{"game":"英雄联盟","desc":"就是这么任性"}]}}";
            Map<String, String> keyMap = new HashMap<String, String>();
            keyMap.put("name", "XingMing");
            keyMap.put("user", "YongHu");
            keyMap.put("desc", "MiaoShu");
            JSONObject jsonObj = JSONUtil.changeJsonObj(JSONObject.parseObject(jsonStr),keyMap);
            System.out.println("换值结果 》》 " + jsonObj.toString());
        }
    }
  • 相关阅读:
    常用的正则表达式
    vue多页面应用
    webpack + jquery + bootstrap 环境配置
    Goroutine的几个例子
    设置css通用字体
    简单的gulpfile.js参数配置
    1:时间戳转换成年月日函数,2:url截取参数方法,3:弹窗自定义方法 4:点击按钮加入购物车
    github上比较全的知识
    秒杀倒计时
    正则校验手机号码并获取手机验证码倒计时的实例
  • 原文地址:https://www.cnblogs.com/shihaiming/p/10208436.html
Copyright © 2011-2022 走看看