Java工具:驼峰Json与下划线Json相互转化(递归)

 

1.ExpressUtils 工具:https://blog.csdn.net/bestxianfeng163/article/details/105856610

2.HumpLineUtils工具:https://blog.csdn.net/bestxianfeng163/article/details/102589532

package com.zycfc.mpc.process.util;
import java.util.Set;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
public class JsonHumpLineUtils {
	public static void main(String[] args) {
		String json2="{}";
		System.out.println(transfer(json2));
	}
	/*
	 * 递归驼峰json 转化下划线json
	 */
	public static JSONObject transfer(String json) {
		JSONObject objTem = JSON.parseObject(json);
		return transHump(objTem);
	}
	/*
	 * 递归Json驼峰转下划线json
	 * */
	private static JSONObject transLine(JSONObject objTem) {
		JSONObject jsonObject = new JSONObject();
		Set keySet = objTem.keySet();
		for (String key : keySet) {
			Object objR = objTem.get(key);
			Class type = objR.getClass();
			String express = ExpressUtils.getExpress(ExpressUtils.classLists());
			if (ExpressUtils.judge(express, type)) {
				jsonObject.put(HumpLineUtils.transline(key, "Lower"), objR);
				continue;
			}
			if (objR instanceof JSONObject) {
				JSONObject deal = transLine((JSONObject) objR);
				jsonObject.put(HumpLineUtils.transline(key, "Lower"), deal);
				continue;
			}
			if (objR instanceof JSONArray) {
				JSONArray jsonA = new JSONArray();
				JSONArray jsonArray = objTem.getJSONArray(key);
				for (int i = 0; i < jsonArray.size(); i++) {
					JSONObject jsonDeal = transLine(jsonArray.getJSONObject(i));
					jsonA.add(jsonDeal);
				}
				jsonObject.put(HumpLineUtils.transline(key, "Lower"), jsonA);
			}
		}
		return jsonObject;
	}
	/*
	 * 递归下划线Json转驼峰json
	 * */
	private static JSONObject transHump(JSONObject objTem) {
		JSONObject jsonObject = new JSONObject();
		Set keySet = objTem.keySet();
		for (String key : keySet) {
			Object objR = objTem.get(key);
			Class type = objR.getClass();
			String express = ExpressUtils.getExpress(ExpressUtils.classLists());
			if (ExpressUtils.judge(express, type)) {
				jsonObject.put(HumpLineUtils.transHump(key), objR);
				continue;
			}
			if (objR instanceof JSONObject) {
				JSONObject deal = transHump((JSONObject) objR);
				jsonObject.put(HumpLineUtils.transHump(key), deal);
				continue;
			}
			if (objR instanceof JSONArray) {
				JSONArray jsonA = new JSONArray();
				JSONArray jsonArray = objTem.getJSONArray(key);
				for (int i = 0; i < jsonArray.size(); i++) {
					JSONObject jsonDeal = transHump(jsonArray.getJSONObject(i));
					jsonA.add(jsonDeal);
				}
				jsonObject.put(HumpLineUtils.transHump(key), jsonA);
			}
		}
		return jsonObject;
	}
}

 

你可能感兴趣的:(工具类)