魅力程序猿

  • 首页
  • Java
  • Android
  • APP
    • 扑克计分器
    • Video Wallpaper
  • 联系我
  • 关于我
  • 资助
道子
向阳而生
  1. 首页
  2. Android
  3. 正文

用Gson实现泛型解析

2016年11月28日 14352点热度 0人点赞 2条评论

用Gson(URL:https://github.com/google/gson)解析Json方便之处我就不多说了,不过,要是针对没有实体类都写对应的解析方式是不是就有点晕了呢?代码一样就是解析的对象不一样,那么为什么不使用泛型呢?你会说我用了呀,会报错呀(java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap cannot be cast to xxx)?是的,因为你没有写好,所以报错。

下面来看一下,我调通的代码吧,希望能帮助你。

ParserBase.java

package com.aoaoyi.gson.parser;

import android.text.TextUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.util.List;

/**
 * 解析对象基类
 *
 * Created by yuzhenbei on 2015/7/25.
 */
public class ParserBase {

    /**
     * 从JSON字符串中反序列化T对象
     *
     * @param pJsonStr JSON字符串
     * @param pClass 对象的Class
     * @param <T> 将要反序列化成的T对象
     * @return T对象
     */
    public static <T> T parserTFromJson(String pJsonStr, final Class<T> pClass){
        T _T;
        try{
            if (!TextUtils.isEmpty(pJsonStr)){
                Gson _Gson = new Gson();
                _T = _Gson.fromJson(pJsonStr, pClass);
            }else {
                _T = null;
            }
        }catch (Exception e){
            e.printStackTrace();
            _T = null;
        }
        return _T;
    }

    /**
     * 序列化T对象为JSON字符串
     *
     * @param pT T对象
     * @param <T> 将要序列化的T对象
     * @return JSON字符串
     */
    public static <T> String parserTToJson(T pT){
        String _JosnStr;
        try{
            if (pT != null) {
                Gson _Gson = new Gson();
                _JosnStr = _Gson.toJson(pT);
            }else {
                _JosnStr = "";
            }
        }catch (Exception e){
            e.printStackTrace();
            _JosnStr = "";
        }
        return _JosnStr;
    }

    /**
     * 从JSON字符串中反序列化List<T>集合对象
     *
     * @param pJsonData JSON字符串
     * @param pClass T对象的Class
     * @param <T> 对象类型
     * @return List<T>集合对象
     */
    public static <T> List<T> parserListTFromJson(final String pJsonData, final Class<T> pClass){
        List<T> _TList;
        try{
            if (!TextUtils.isEmpty(pJsonData)){
                Gson _Gson = new Gson();
                _TList = _Gson.fromJson(pJsonData, new ListOfJson<T>(pClass));
            }else {
                _TList = null;
            }
        }catch (Exception e){
            e.printStackTrace();
            _TList = null;
        }
        return _TList;
    }

    /**
     * 序列化List<T>集合对象为JSON字符串
     *
     * @param pListT List<T>集合对象
     * @param <T> 对象类型
     * @return JSON字符串
     */
    public static <T> String parserListTToJson(List<T> pListT){
        String _JosnStr;
        try{
            if (pListT != null) {
                Gson _Gson = new Gson();
                _JosnStr = _Gson.toJson(pListT);
            }else {
                _JosnStr = "";
            }
        }catch (Exception e){
            e.printStackTrace();
            _JosnStr = "";
        }
        return _JosnStr;
    }
}

其中用到的ListOfJson.class

package com.aoaoyi.gson.parser;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

/**
 * class can store the exactly type of list
 *
 * Created by yuzhenbei on 2015/7/25.
 */
public class ListOfJson<T> implements ParameterizedType {

    private Class<?> mType;

    public ListOfJson(Class<T> pType) {
        this.mType = pType;
    }

    /**
     * Returns an array of the actual type arguments for this type.
     * <p/>
     * If this type models a non parameterized type nested within a
     * parameterized type, this method returns a zero length array. The generic
     * type of the following {@code field} declaration is an example for a
     * parameterized type without type arguments.
     * <p/>
     * <pre>
     * A&lt;String&gt;.B field;
     *
     * class A&lt;T&gt; {
     *     class B {
     *     }
     * }</pre>
     *
     * @return the actual type arguments
     * @throws TypeNotPresentException             if one of the type arguments cannot be found
     * @throws MalformedParameterizedTypeException if one of the type arguments cannot be instantiated for some
     *                                             reason
     */
    @Override
    public Type[] getActualTypeArguments() {
        return new Type[] {mType};
    }

    /**
     * Returns the parent / owner type, if this type is an inner type, otherwise
     * {@code null} is returned if this is a top-level type.
     *
     * @return the owner type or {@code null} if this is a top-level type
     * @throws TypeNotPresentException             if one of the type arguments cannot be found
     * @throws MalformedParameterizedTypeException if the owner type cannot be instantiated for some reason
     */
    @Override
    public Type getOwnerType() {
        return null;
    }

    /**
     * Returns the declaring type of this parameterized type.
     * <p/>
     * The raw type of {@code Set<String> field;} is {@code Set}.
     *
     * @return the raw type of this parameterized type
     */
    @Override
    public Type getRawType() {
        return List.class;
    }
}

 

相关阅读:

1. Charles最新版破解注册方法

2. Android面试题18–ADB的常用命令

3.Android面试题16–代码混淆(Proguard)

 

 

标签: Gson实现泛型解析 用Gson实现泛型解析
最后更新:2016年11月28日

daozi

这个人很懒,什么都没留下

点赞
< 上一篇
下一篇 >

文章评论

  • Eldora

    I recommend NewPages.com for reviews of literary magazines. Many of these “little mags” also have wonderful art along with poetry, fiction, and creative nonfiction (as well as book reviews) by up and coming visual and textual artists. Check out Ne8&Pgesa#w211;the reviews include websites and summaries. Each review is a quick, helpful read.

    2016年12月18日
    回复
  • Heaven

    I am totally wowed and prapreed to take the next step now.

    2016年12月19日
    回复
  • razz evil exclaim smile redface biggrin eek confused idea lol mad twisted rolleyes wink cool arrow neutral cry mrgreen drooling persevering
    回复 Eldora 取消回复
    搜索
    联系方式

    QQ群:179730949
    QQ群:114559024
    欢迎您加入Android大家庭
    本人QQ:136049925

    赐我一丝安慰
    给我一点鼓励

    COPYRIGHT © 2023 魅力程序猿. ALL RIGHTS RESERVED.

    Theme Kratos Made By Seaton Jiang

    豫ICP备15000477号