欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Gson替换json中name的值

程序员文章站 2022-05-28 16:52:35
...
package com.vip.gsontest.tools;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonNull;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
/**
 * 日常中经常需要把json转成对象或者把对象转成json,但对应属性名与原来json的key不一致的情况,经常发生,通过该工具,可以进行转换
 * 
 * @author laien.liang
 *
 */
public class GsonUtil {

	public static JsonElement replaceKey(JsonElement source,Map<String, String> rep) {
		if (source == null || source.isJsonNull()) {
			return JsonNull.INSTANCE;
		}
		if (source.isJsonPrimitive()) {
			return source;
		}
		if (source.isJsonArray()) {
			JsonArray jsonArr = source.getAsJsonArray();
			JsonArray jsonArray = new JsonArray();
			jsonArr.forEach(item -> {
				jsonArray.add(replaceKey(item, rep));
			});
			return jsonArray;
		}
		if (source.isJsonObject()) {
			JsonObject jsonObj = source.getAsJsonObject();
			Iterator<Entry<String, JsonElement>> iterator = jsonObj.entrySet().iterator();
			JsonObject newJsonObj = new JsonObject();
			iterator.forEachRemaining(item -> {
				String key = item.getKey();
				JsonElement value = item.getValue();
				if (rep.containsKey(key)) {
					String newKey = rep.get(key);
					key = newKey;
				}
				newJsonObj.add(key, replaceKey(value, rep));
			});

			return newJsonObj;
		}
		return JsonNull.INSTANCE;
	}
	public static void main(String[] args) {
		String json = "{\"order_sn\":\"14031000273822\",\"carriers_code\":1100000357,\"carrier\":\"浙*尔快递\",\"package_type\":2,\"packages\":[{\"0\":{\"good_sn\":\"ALM2236W36\",\"amount\":\"2\"},\"1\":{\"good_sn\":\"ALM2236W37\",\"amount\":\"2\"},\"transport_no\":\"test5715A\"},{\"0\":{\"good_sn\":\"ALM2236W35\",\"amount\":\"2\"},\"transport_no\":\"test5715B\"}]}";
		JsonElement jsonEle = new JsonParser().parse(json);
		HashMap<String, String> rep = new HashMap<String, String>();
		rep.put("order_sn", "order_id");
		rep.put("carriers_code", "carrier_code");
		rep.put("good_sn", "barcode");
		JsonElement replaceKey = replaceKey(jsonEle, rep);
		System.out.println(replaceKey.toString());

	}

}