Android gson使用

来源:互联网 发布:用python做数据分析pdf 编辑:程序博客网 时间:2024/05/16 08:25

string转换为object

Type type = new TypeToken<QuestionTempSave<SingleTemp>>() {}.getType(); QuestionTempSave<SingleTemp> questionTempSave = (QuestionTempSave) GsonUtil.getInstance().fromJson(jsonString, type);

GsonUtil

public class GsonUtil {    private static GsonUtil mInstance;    public static GsonUtil getInstance() {        if (mInstance == null)            mInstance = new GsonUtil();        return mInstance;    }    private Gson gson;    private GsonUtil() {        gson = new Gson();    }    public Object fromJson(String str, Type type) {        try {            return gson.fromJson(str, type);        } catch (Exception e) {            Log.i("GsonUtil", "fromJson出错");            return null;        }    }    public String toJson(Object object) {        try {            return gson.toJson(object);        } catch (Exception e) {            Log.i("GsonUtil", "toJson出错");            return null;        }    }}
0 0