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<String> 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<String> 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;
	}
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章