谷歌的json解析器Gson在Android/Java中的常用工具类

35 篇文章 1 订阅
UesGsonParser是一个实现了Gson库的工具类,支持子类与JSON字符串之间的相互转换。它可以创建Gson实例,并根据是否仅解析@Expose注解的字段进行配置。此外,还提供了将对象转换为JSON字符串,从JSON字符串反序列化为对象的方法,以及处理JSON解析异常的功能。
摘要由CSDN通过智能技术生成

gson解析器,可实现子类和json字符串之间互转

package com.hulk.ues.core;

import android.text.TextUtils;
import android.util.Log;

import com.qax.ues.server.util.UesCoreUtils;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.ArrayList;

/**
 * gson解析器,可实现子类和json字符串之间互转
 *
 * @Author: zhanghao
 * @Time: 2020-04-28 14:59:15
 * @Version: 1.0.0
 */
public class UesGsonParser {
    private static final String TAG = "UesGsonParser";
    /**
     * 是否补货异常
     */
    public static final boolean CATCH_EXCEPTION = false;
    /**
     * 原始的json字符串
     */
    protected transient String rawJson;
    protected transient Throwable parsingError;

    /**
     * 是否只解析(@Expose)修饰的对象字段
     */
    public static final boolean DEFAULT_EXPOSE_ANNOTATION_MODE = false;
    /**
     * 是否只解析(@Expose)修饰的对象字段
     * <p>实体类使用@Expose注释事必须使用; 创键的Gson对象才只能解析出被注释的字段来.
     * <p>Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
     */
    protected transient boolean exposeAnnotationMode = DEFAULT_EXPOSE_ANNOTATION_MODE;

    public void setRawJson(String rawJson) {
        this.rawJson = rawJson;
    }

    public String getRawJson() {
        return rawJson;
    }

    public Throwable getParsingError() {
        return parsingError;
    }

    public void setParsingError(Throwable parsingError) {
        this.parsingError = parsingError;
    }

    public boolean isExposeAnnotationMode() {
        return exposeAnnotationMode;
    }

    public void setExposeAnnotationMode(boolean exposeAnnotationMode) {
        this.exposeAnnotationMode = exposeAnnotationMode;
    }

    /**
     * 用于解析的Gson对象
     * <p>子类可以复写
     * @return
     */
    protected Gson onGson() {
        return createGson(isExposeAnnotationMode());
    }

    /**
     * 创键解析的Gson对象
     * <p>子类可以换成
     * @param exposeAnnotationMode
     * @return
     */
    public static Gson createGson(boolean exposeAnnotationMode) {
        if (exposeAnnotationMode) {
            return new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
        } else {
            return new Gson();
        }
    }

    /**
     * 创键解析的Gson对象
     * <p>子类可以换成
     * @param exposeAnnotationMode
     * @return
     */
    public static Gson createGson(boolean exposeAnnotationMode, Type type, Object typeAdapter) {
        Gson gson;
        if (exposeAnnotationMode) {
            gson = createExposedGson(type, typeAdapter);
        } else if (typeAdapter != null) {
            gson = createGson(type, typeAdapter);
        } else {
            gson = new Gson();
        }
        return gson;
    }

    /**
     * 创键Expose修饰的的Gson对象
     * @param type
     * @param typeAdapter
     * @return
     */
    public static Gson createExposedGson(Type type, Object typeAdapter) {
        GsonBuilder builder = new GsonBuilder();
        builder.excludeFieldsWithoutExposeAnnotation().create();
        registerTypeAdapter(builder, type, typeAdapter);
        return builder.create();
    }

    /**
     * 创键Expose修饰的的Gson对象
     * @return
     */
    public static Gson createExposedGson() {
        return createExposedGson(null, null);
    }

    /**
     * 创键类型适配器Gson对象
     * GsonBuilder builder = new GsonBuilder();
     * builder.registerTypeAdapter(new TypeToken<UesLoginResponseData>() {
     * }.getType(), new UesTypeAdapter());
     * Gson gson = builder.create();
     * @param type 实体类的类型, eg: new TypeToken<UesLoginResponseData>() {}.getType()
     * @param typeAdapter  类型适配器 eg: new UesTypeAdapter()
     * @return
     */
    public static Gson createGson(Type type, Object typeAdapter) {
        GsonBuilder builder = new GsonBuilder();
        registerTypeAdapter(builder, type, typeAdapter);
        Gson gson = builder.create();
        return gson;
    }

    /**
     * 创键自定义类型适配器Gson对象
     * @param type 实体类的类型, eg: new TypeToken<UesLoginResponseData>() {}.getType()
     * @return
     */
    public static Gson createUesTypeAdapterGson(Type type) {
        if (type == null) {
            throw new IllegalArgumentException("type == null");
        }
        Object typeAdapter = new UesTypeAdapter();
        return createGson(type, typeAdapter);
    }

    /**
     * 注册解析的Gson对象的类型适配器
     * @param builder  GsonBuilder eg: new GsonBuilder();
     * @param type  实体类的类型, eg: new TypeToken<UesLoginResponseData>() {}.getType()
     * @param typeAdapter 类型适配器 eg: new UesTypeAdapter()
     * @return
     */
    public static boolean registerTypeAdapter(GsonBuilder builder, Type type, Object typeAdapter) {
        if (builder == null || typeAdapter == null) {
            return false;
        }
        if (type == null) {
            //typeAdapter非null,type必须非空
            throw new IllegalArgumentException("registered type is bull, please create it");
        }
        builder.registerTypeAdapter(type, typeAdapter);
        return true;
    }

    /**
     * 创键解析的Gson对象
     * @return
     */
    public static Gson createGson() {
        return createGson(false);
    }

    /**
     * 对象转化为Json
     * @return
     */
    public String toJson() {
        return toJson(this, isExposeAnnotationMode());
    }

    /**
     * 对象转化为Json
     * @return
     */
    public JSONObject toJsonObject() {
        String json = toJson();
        try {
            return new JSONObject(json);
        } catch (JSONException e) {
            Log.e(TAG, "toJsonObject: " + e + ", json= " + json);
        }
        return null;
    }

    public static String toJson(Object src) {
        return toJson(src, false);
    }

    /**
     * 实体对象转化为json夫妇穿
     * @param src
     * @param exposeAnnotationMode
     * @return
     */
    public static String toJson(Object src, boolean exposeAnnotationMode) {
        try {
            Gson gson = createGson(exposeAnnotationMode);
            return gson.toJson(src);
        } catch (Exception e) {
            Log.e(TAG, "toJson failed: " + e + ", src= " + src);
            throw e;
        }
    }

    /**
     * Json转化为对象
     * @param jsonObject
     * @param classOfT
     * @param <T>
     * @return
     */
    public static <T extends UesGsonParser> T fromJSONObject(JSONObject jsonObject, Class<T> classOfT) {
        if (jsonObject == null) {
            Log.e(TAG, "fromJSONObject failed: jsonObject is null");
            return null;
        }
        return fromJson(jsonObject.toString(), classOfT);
    }

    /**
     * Json转化为对象
     * @param jsonStr
     * @param classOfT
     * @param <T>
     * @return
     */
    public static <T extends UesGsonParser> T fromJsonStr(String jsonStr, Class<T> classOfT) {
        return fromJson(jsonStr, classOfT);
    }

    public static <T extends UesGsonParser> T fromJson(String json, Class<T> classOfT) {
        return fromJson(json, classOfT, CATCH_EXCEPTION);
    }

    /**
     * Json转化为对象
     * @param json
     * @param classOfT
     * @param catchException 如果json解析失败是否需要捕获异常
     * @param <T>
     * @return
     */
    public static <T extends UesGsonParser> T fromJson(String json, Class<T> classOfT, boolean catchException) {
        if (catchException) {
            try {
                return fromJsonBase(json, classOfT);
            } catch (Throwable e) {
                Log.e(TAG, "### fromJson failed catch: " + e + ", classOfT= " + classOfT + ", json= " + json, e);
                //构建错误信息的 UesGsonParser 对象, 把json数据放在classOfT中解析,返回client段,便于通过json分析问题
                T error = createParsingError(json, classOfT, e);
                Log.w(TAG, "fromJson: return parsing error: " + error);
                return error;
            }
        }
        return fromJsonBase(json, classOfT);
    }

    /**
     * 创键加息失败错误
     * @param json
     * @param classOfT
     * @param tr
     * @param <T>
     * @return
     */
    public static <T extends UesGsonParser> T createParsingError(String json, Class<T> classOfT, Throwable tr) {
        UesGsonParser parser = new UesGsonParser();
        parser.setRawJson(json);
        parser.setParsingError(tr);
        return fromJsonBase(parser.toJson(), classOfT);
    }

    /**
     * Json转化为对象,如果字符串非法或者错误,直接抛出异常
     * @param json
     * @param classOfT
     * @param <T>
     * @return
     */
    public static <T extends UesGsonParser> T fromJsonBase(String json, Class<T> classOfT) {
        if (TextUtils.isEmpty(json)) {
            Log.e(TAG, "fromJsonBase: Ignored json is empty, classOfT: " + classOfT);
            return null;
        }
        Gson gson = createGson();
        T bean = gson.fromJson(json, classOfT);
        if (bean != null) {
            bean.setRawJson(json);
            bean.parseCustomError(json);
        } else {
            Log.e(TAG, "fromJsonBase: parsed bean is null from json: " + json + ", classOfT: " + classOfT);
        }
        return bean;
    }

    /**
     * 通用反序列化
     * @param json
     * @param classOfT
     * @param <T>
     * @return
     */
    public static <T> T fromJsonCommon(String json, Class<T> classOfT) {
        if (TextUtils.isEmpty(json)) {
            Log.e(TAG, "fromJsonCommon: Ignored json is empty, classOfT: " + classOfT);
            return null;
        }
        Gson gson = createGson();
        T bean = gson.fromJson(json, classOfT);
        if (bean != null) {
            // do nothing
        } else {
            Log.e(TAG, "fromJsonCommon: parsed bean is null from json: " + json + ", classOfT: " + classOfT);
        }
        return bean;
    }

    protected void parseCustomError(String json) {
        //sub class impl
    }

    /**
     *  json数组对象转化为对象数组
     * @param jsonArray
     * @param classOfT
     * @param <T>
     * @return
     */
    public static <T extends UesGsonParser> ArrayList<T> fromJsonArrayOpt(JSONArray jsonArray, Class<T> classOfT) {
        if (jsonArray == null) {
            Log.e(TAG, "fromJsonArrayOpt failed: jsonArray is null");
            return null;
        }
        ArrayList<T> list = new ArrayList<>();
        int length = jsonArray.length();
        for (int i = 0; i < length; i++) {
            JSONObject json = jsonArray.optJSONObject(i);
            T detail = fromJSONObject(json, classOfT);
            if (detail != null) {
                list.add(detail);
            }
        }
        return list;
    }

    public static <T extends UesGsonParser> ArrayList<T> fromJsonArrayOpt(String jsonArrayStr, Class<T> classOfT) {
        try {
            return fromJsonArrayOpt(new JSONArray(jsonArrayStr), classOfT);
        } catch (JSONException e) {
            Log.e(TAG, "fromJsonArrayOpt failed: " + e + ", classOfT= " + classOfT + ", jsonArrayStr= " + jsonArrayStr);
        }
        return null;
    }

    /**
     * json数组字符串转化为对象数组
     * eg:
     * String userJson = "[{'name': 'Alex','id': 1}, "
     *                 + "{'name': 'Brian','id':2}, "
     *                 + "{'name': 'Charles','id': 3}]";
     * Gson gson = new Gson();
     * User[] userArray = gson.fromJson(userJson, User[].class);
     *
     * @param jsonArrayStr
     * @param classOfTArray 数组的class eg User[].class
     * @param <T>
     * @return
     */
    public static <T> T[] fromJsonArrayBase(String jsonArrayStr, Class classOfTArray) {
        Gson gson = createGson();
        T[] array = (T[]) gson.fromJson(jsonArrayStr, classOfTArray);
        return array;
    }

    /**
     * json数组字符串转化为对象数组
     * eg:
     * String userJson = "[{'name': 'Alex','id': 1}, "
     *                 + "{'name': 'Brian','id':2}, "
     *                 + "{'name': 'Charles','id': 3}]";
     * Gson gson = new Gson();
     * User[] userArray = gson.fromJson(userJson, User[].class);
     *
     * @param jsonArrayStr
     * @param classOfTArray 数组的class eg User[].class
     * @param <T>
     * @return
     */
    public static <T> T[] fromJsonArray(String jsonArrayStr, Class classOfTArray) {
        if (CATCH_EXCEPTION) {
            try {
                return fromJsonArrayBase(jsonArrayStr, classOfTArray);
            } catch (Exception e) {
                Log.e(TAG, "fromJsonArray failed: " + e + ", classOfTArray= " + classOfTArray + ", jsonArrayStr= " + jsonArrayStr);
                return null;
            }
        }
        return fromJsonArrayBase(jsonArrayStr, classOfTArray);
    }

    public static Object opt(String json, String name) {
        try {
            JSONObject jsonObject = new JSONObject(json);
            return jsonObject.opt(name);
        } catch (Exception e) {
            Log.e(TAG, "opt failed: " + e + ", json= " + json);
        }
        return "";
    }

    public static String optString(String json, String name) {
        try {
            JSONObject jsonObject = new JSONObject(json);
            return jsonObject.optString(name, "");
        } catch (Exception e) {
            Log.e(TAG, "optString failed: " + e + ", json= " + json);
        }
        return "";
    }

    public static String optInt(String json, String name) {
        try {
            JSONObject jsonObject = new JSONObject(json);
            return jsonObject.optString(name, "");
        } catch (Exception e) {
            Log.e(TAG, "optInt failed: " + e + ", json= " + json);
        }
        return "";
    }

    public static boolean optBoolean(String json, String name) {
        try {
            JSONObject jsonObject = new JSONObject(json);
            return jsonObject.optBoolean(name, false);
        } catch (Exception e) {
            Log.e(TAG, "optBoolean failed: " + e + ", json= " + json);
        }
        return false;
    }

    public static JSONObject optJSONObject(String json, String name) {
        try {
            JSONObject jsonObject = new JSONObject(json);
            return jsonObject.optJSONObject(name);
        } catch (Exception e) {
            Log.e(TAG, "optJSONObject failed: " + e + ", json= " + json);
        }
        return null;
    }

    public static JSONArray optJSONArray(String json, String name) {
        try {
            JSONObject jsonObject = new JSONObject(json);
            return jsonObject.optJSONArray(name);
        } catch (Exception e) {
            Log.e(TAG, "optJSONArray failed: " + e + ", json= " + json);
        }
        return null;
    }

    public static boolean exists(String json, String name) {
        return opt(json, name) != null;
    }

    /**
     * 个对象内容是否相等
     * @param a
     * @param b
     * @return
     */
    public static boolean equals(Object a, Object b) {
        return UesCoreUtils.equals(a, b);
    }

    /**
     * 获取 hashcode
     * <p> ^(异或运算符)
     * @param values
     * @return
     */
    public static int hash(Object... values) {
        return UesCoreUtils.hash(values);
    }

    /**
     * 日志打印, DEBUG模式打印
     * @param tag TAG
     * @param func 函数名
     * @param msgFormat 信息体
     * @param params 参数值
     */
    public static void log(String tag, String func, String msgFormat, Object... params) {
        HulkLogger.log(tag, func, msgFormat, params);
    }

    @Override
    public String toString() {
        return "UesGsonParser{" +
                "rawJson=" + rawJson +
                ", parsingError=" + parsingError +
                '}';
    }
}

其他的引用类在附件中,此处不再贴出代码

附件源代码连接: gson解析器实现json和实体类对象互转源代码-Android文档类资源-CSDN下载

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值