package com.brilliance.isc.swift.objmtconvert.util;

import com.google.gson.*;
import org.apache.commons.lang3.StringUtils;

public class SSTFGson {

    private static final Gson GSON_INSTANCE = new Gson();
    private static final JsonParser GSON_PARSER = new JsonParser();

    public static Gson getInstance() {
        return GSON_INSTANCE;
    }
    public static JsonParser getGsonParser() {
        return GSON_PARSER;
    }

    /**
     * 获取JSON字符窜中的值
     * @param gsonStr
     * @param path
     * @return
     */
    public static String getValueByPath(String gsonStr,String path) {
        if (StringUtils.isBlank(gsonStr) || StringUtils.isBlank(path)) {
            return null;
        }
        JsonElement element = GSON_PARSER.parse(gsonStr);
        String[] paths = path.split("/");
        for (String key : paths) {
            if (StringUtils.isBlank(key)) {
                continue;
            }
            if (null == element || !element.isJsonObject()) {
                return null;
            }
            element = ((JsonObject) element).get(key);
        }
        return element == null ? null : element.getAsString();
    }

    /** 格式化JSON字符窜
     * @param jsonStr
     * @return
     */
    public static String toPrettyJson(String jsonStr) {
        if (StringUtils.isBlank(jsonStr)) {
            return jsonStr;
        }
        try {
            return new GsonBuilder().setPrettyPrinting().create().toJson(SSTFGson.getGsonParser().parse(jsonStr));
        } catch (Exception e) {
            return jsonStr;
        }
    }

}
