fastjson转bean和集合的实用方法

来源:互联网 发布:空调的选购 知乎 编辑:程序博客网 时间:2024/06/06 07:21
 public static <T extends BaseBean> ArrayList<T> strToList(String dataStr, Class<T> targetClass) {

        List<T> list = null;

        try {
            list = JSON.parseArray(dataStr, targetClass);
        } catch (com.alibaba.fastjson.JSONException exception) {
            return new ArrayList<T>();
        }

        if (list != null) {
            return new ArrayList<T>(list);
        } else {
            return new ArrayList<T>();
        }
    }

    public static <T extends BaseBean> T strToBean(String dataStr, Class<T> targetClass) {

        T t = null;
        try {
            t = JSON.parseObject(dataStr, targetClass);
        } catch (com.alibaba.fastjson.JSONException exception) {
            t = null;
        }

        if (t == null) {
            try {
                t = targetClass.newInstance();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return t;

    }

     BaseBean为bean的基类,需要实现序列化

0 0