package com.ag.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

/**
 * Created by yangxh on 2019/9/18.
 */
public class JSONUtil {

    public static void main(String[] args) {
        String test = "{\"fpkjxxXmxxs\": {\n" +
                "      \"-class\": \"FPKJXX_XMXX\",\n" +
                "      \"-size\": \"1\",\n" +
                "      \"fpkXmxx\": [{\n" +
                "        \"xmmc\": \"ddddff\",\n" +
                "        \"xmdw\": \"fffff\",\n" +
                "        \"gggg\": \"cccc\",\n" +
                "        \"zzzz\": \"fds\",\n" +
                "        \"kce\": \"扣除额\",\n" +
                "        \"xmje\": \"项目金额\",\n" +
                "        \"sl\": \"税率\",\n" +
                "        \"se\": \"税额\",\n" +
                "      }]\n" +
                "    }}";
        JSONObject json = JSON.parseObject(test);
        System.out.println(JSON.toJSONString(json));
        System.out.println(JSON.toJSONString(transKeyUpper(json)));
    }

    public static JSONObject transKeyUpper(JSONObject o1){

        JSONObject o2 = new JSONObject();
        o1.forEach((key, value) -> {
            if(value instanceof JSONObject){
                o2.put(key, transKeyUpper((JSONObject)value));
            }else if(value instanceof JSONArray){
                o2.put(key, transArray(o1.getJSONArray(key)));
            }else if (key.startsWith("@")){
                o2.put(key, value);
            } else {
                o2.put(key, value);
            }
        });
        return o2;
    }

    public static JSONArray transArray(JSONArray o1){
        JSONArray o2 = new JSONArray();
        for (int i = 0; i < o1.size(); i++) {
            Object jArray=o1.getJSONObject(i);
            if(jArray.getClass().toString().endsWith("JSONObject")){
                o2.add(transKeyUpper((JSONObject)jArray));
            }else if(jArray.getClass().toString().endsWith("JSONArray")){
                o2.add(transArray((JSONArray)jArray));
            }
        }
        return o2;
    }

    private static String toUpper(String param) {
        return toLower(param).toUpperCase();
    }

    private static String toLower(String param) {
        StringBuilder sb = new StringBuilder();
        char[] col = param.toCharArray();
        for (char ch : col) {
            if (Character.isUpperCase(ch)) {
                sb.append("_").append(Character.toLowerCase(ch));
            } else {
                sb.append(ch);
            }
        }
        return sb.toString();
    }

}
