package com.jianshui.common.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jianshui.common.constant.Constants;

public class JsonKeyCase {

    /*
     *  默认转大写
     */
    public static JSONObject JsonKeyCase(JSONObject data){
        return JsonKeyCase(data,Constants.INT_0);
    }

    /*
     *  json对象中的key转换
     */
    public static JSONObject JsonKeyCase(JSONObject data,int flag){

        JSONObject newData = new JSONObject();

        if(data == null ){
            return data;
        }

        for (String key : data.keySet()) {

            Object value = data.get(key);

            String name = value != null ? value.getClass().getName() : "";

            if (name.endsWith(Constants.JSONObject)){

                value = JsonKeyCase((JSONObject) value,flag);


            }else if (name.endsWith(Constants.JSONArray)){

                value = arrayKeyrCase((JSONArray) value,flag);

            }

            String newKey;

            if (flag == Constants.INT_0) {
                newKey = key.toUpperCase();
            }else {
               newKey = key.toLowerCase();
            }

            newData.put(newKey, value);
        }

        return newData;

    }

    /*
     *  默认转大写
     */
    public static JSONArray arrayKeyrCase(JSONArray data){
        return arrayKeyrCase(data,Constants.INT_0);
    }


    /*
     *  jsonArray转换
     */

    public static JSONArray arrayKeyrCase(JSONArray data,int flag){

        if (data == null){
            return data;
        }

        JSONArray newArray = new JSONArray();
        for (Object datum : data) {

            String name = datum.getClass().getName();

            if (name.endsWith(Constants.JSONObject)){

                datum = JsonKeyCase((JSONObject) datum,flag);

            }else if (name.endsWith(Constants.JSONArray)){

                datum = arrayKeyrCase((JSONArray) datum,flag);

            }
            newArray.add(datum);
        }

        return newArray;
    }

}
