json解析-fastjson封装

来源:互联网 发布:北京宝库在线网络 编辑:程序博客网 时间:2024/06/05 01:53

不少项目中用到阿里的fastjson.jar去解析或者组装json,当转换错误或者解析异常(fastjson.jar在序列号对象时候,会偶现的报异常),所以使用前最后自己封装一层,加上异常的补获,防止第三方jar包的异常导致自身应用crash。

封装代码如下:

package com.focustech.android.mt.parent.util;import android.util.Log;import com.alibaba.fastjson.JSONArray;import com.alibaba.fastjson.JSONObject;import java.util.List;/** * Created by caoyinfei on 2016/4/27. */public class JsonHelper {    /**     * 把json string 转化成类对象     *     * @param str     * @param t     * @return     */    public static <T> T parseObject(String str, Class<T> t) {        try {            if (str != null && !"".equals(str.trim())) {                T res = JSONArray.parseObject(str.trim(), t);                return res;            }        } catch (Exception e) {            Log.e("数据转换出错", "exception:" + e.getMessage());        }        return null;    }    /**     * 把json string 转化成类对象     *     * @param str     * @param t     * @return     */    public static <T> List<T> parseArray(String str, Class<T> t) {        try {            if (str != null && !"".equals(str.trim())) {                List<T> res = JSONArray.parseArray(str.trim(), t);                return res;            }        } catch (Exception e) {            Log.e("数据转换出错", "exception:" + e.getMessage());        }        return null;    }    /**     * 把类对象转化成json string     *     * @param t     * @return     */    public static <T> String toJson(T t) {        try {            return JSONObject.toJSONString(t);        } catch (Exception e) {            Log.e("数据转换出错", "exception:" + e.getMessage());        }        return "";    }}
0 0