com.ai2020lab.aiutils.common.JsonUtils.java Source code

Java tutorial

Introduction

Here is the source code for com.ai2020lab.aiutils.common.JsonUtils.java

Source

/*
 * Copyright 2015 Justin Z
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.ai2020lab.aiutils.common;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

/**
 * JSONgoogle GSON ?
 * Created by Justin on 2015/7/14.
 * Email:502953057@qq.com,zhenghx3@asiainfo.com
 */
public class JsonUtils {

    private final static String TAG = JsonUtils.class.getSimpleName();

    private static Gson gson;
    private static JsonParser jsonParser;

    private static ParserType parserType = ParserType.NORMAL;

    /**
     * ?
     */
    private JsonUtils() {
    }

    private static void initGson(ParserType type) {
        if (type == ParserType.EXCLUDE) {
            gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
        } else if (type == ParserType.NORMAL) {
            gson = new GsonBuilder().create();
        }
    }

    // ??
    private static void init(ParserType type) {
        if (jsonParser == null) {
            jsonParser = new JsonParser();
        }
        if (gson == null) {
            initGson(type);
            parserType = type;
        } else {
            if (parserType != type) {
                initGson(type);
                parserType = type;
            }
        }
    }

    /**
     * 
     *
     * @return JsonUtils
     */
    public static JsonUtils getInstance() {
        init(parserType);
        return SingletonHolder.instance;
    }

    /**
     * 
     *
     * @param type ?
     * @return JsonUtils
     */
    public static JsonUtils getInstance(ParserType type) {
        init(type);
        return SingletonHolder.instance;
    }

    /**
     * ?JSON?
     *
     * @param jsonStr ??JSON?
     * @return ?true?false
     */
    public boolean isJsonStrAvailable(String jsonStr) {
        if (jsonStr == null || jsonStr.equals("")) {
            LogUtils.i(TAG, "?JSON?");
            return false;
        }
        try {
            jsonParser.parse(jsonStr);
            return true;
        } catch (Exception e) {
            LogUtils.e(TAG, "?JSON?");
            return false;
        }
    }

    /**
     * ?JsonObject
     *
     * @param jsonStr 
     * @return JsonObject
     */
    public JsonObject stringToJsonObj(String jsonStr) {
        // JSON
        if (jsonStr == null || jsonStr.equals("")) {
            throw new IllegalArgumentException("???JsonObject?");
        }
        JsonElement jsonE = null;
        try {
            jsonE = jsonParser.parse(jsonStr);
        } catch (Exception e) {
            // JSON?JSON??
            LogUtils.e(TAG, " ??JsonObject");
        }
        if (jsonE == null || !jsonE.isJsonObject()) {
            // ?JsonObject?
            LogUtils.e(TAG, "??JsonObject??JsonObject?");
            return null;
        }
        return (JsonObject) jsonE;
    }

    /**
     * ?JsonArray
     *
     * @param jsonStr 
     * @return JsonArray
     */
    public JsonArray stringToJsonArr(String jsonStr) {
        // JSON
        if (jsonStr == null || jsonStr.equals("")) {
            throw new IllegalArgumentException("???JsonArray?");
        }
        JsonElement jsonE = null;
        try {
            jsonE = jsonParser.parse(jsonStr);
        } catch (Exception e) {
            // JSON?JSON??
            LogUtils.e(TAG, " ??JsonArray");
        }
        if (jsonE == null || !jsonE.isJsonArray()) {
            // ?JsonArray?
            LogUtils.e(TAG, "??JsonArray??JsonArray?");
            return null;
        }
        return (JsonArray) jsonE;
    }

    /**
     * ?JSONObject??Stringvalue
     *
     * @param key ??
     * @return ??value
     */
    public String getObjStringValue(String key, JsonObject obj) {
        if (key == null || key.equals("")) {
            // Key
            throw new IllegalArgumentException("?key?");
        }
        if (obj == null || !obj.isJsonObject()) {
            // JsonObject??JsonObject
            throw new IllegalArgumentException("?obj?JsonObject?");
        }
        if (!obj.has(key)) {
            // Key
            LogUtils.e(TAG, "objkey'" + key + "' ");
            return null;
        }
        return obj.get(key).getAsString();
    }

    /**
     * ?JSONObject??Integervalue
     *
     * @param key ??
     * @return ??value
     */
    public Integer getObjIntValue(String key, JsonObject obj) {
        if (key == null || key.equals("")) {
            // Key
            throw new IllegalArgumentException("?key?");
        }
        if (obj == null || !obj.isJsonObject()) {
            // JsonObject??JsonObject
            throw new IllegalArgumentException("?obj?JsonObject?");
        }
        if (!obj.has(key)) {
            // Key
            LogUtils.e(TAG, "objkey'" + key + "' ");
            return null;
        }
        return obj.get(key).getAsInt();
    }

    /**
     * POJO?JSON?
     *
     * @param obj POJO
     * @return JSON??null
     */
    public String serializeToJson(Object obj) {
        if (obj == null) {
            LogUtils.i(TAG, "?POJO");
            return null;
        }
        try {
            return gson.toJson(obj);
        } catch (Exception e) {
            // ?
            LogUtils.e(TAG, "POJO?JSON");
        }
        return null;
    }

    /**
     * JSON??POJO
     *
     * @param jsonStr JSON
     * @param cls     ???POJOClass
     * @return POJO?null
     */
    public <T> T deserializeToObj(String jsonStr, Class<T> cls) {
        if (jsonStr == null || jsonStr.equals("")) {
            LogUtils.i(TAG, "deserializeToObj:?jsonStr?");
            return null;
        }
        if (cls == null) {
            LogUtils.i(TAG, "deserializeToObj:?cls?");
            return null;
        }
        try {
            return gson.fromJson(jsonStr, cls);
        } catch (Exception e) {
            // ???
            LogUtils.e(TAG, "JSON???POJO", e);
        }
        return null;
    }

    public enum ParserType {
        NORMAL, EXCLUDE
    }

    private static class SingletonHolder {
        private static final JsonUtils instance = new JsonUtils();
    }
}