Gson反序列化泛型实例
Posted zslm___
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Gson反序列化泛型实例相关的知识,希望对你有一定的参考价值。
1
package com.ppmoney.g2.mapper; import com.google.common.reflect.TypeToken; import com.google.gson.Gson; import com.google.gson.JsonSyntaxException; import java.lang.reflect.Type; public class JsonHelper { public static void main(String[] args) { String respStr = "{\"status\":0,\"msg\":\"\",\"data\":{\"cardNo\":\"23543456345\"}}"; BaseResponse<CardInfo> cardInfo = parseResponse(respStr); System.out.println(cardInfo.data); respStr = "{\"status\":0,\"msg\":\"\",\"data\":{\"id\":\"23543456345\",\"name\":\"张三\"}}"; BaseResponse<UserInfo> userInfo = parseResponse(respStr); System.out.println(userInfo.data); } private static <T> BaseResponse<T> parseResponse(String responseData) throws JsonSyntaxException { Gson gson = new Gson(); Type jsonType = new TypeToken<BaseResponse<T>>() { }.getType(); BaseResponse<T> result = gson.fromJson(responseData, jsonType); return result; } class BaseResponse<T> { private int status; public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public T getData() { return data; } public void setData(T data) { this.data = data; } private String msg; private T data; } class UserInfo { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "UserInfo{" + "name=‘" + name + ‘\‘‘ + ", Id=‘" + Id + ‘\‘‘ + ‘}‘; } public String getId() { return Id; } public void setId(String id) { Id = id; } private String Id; } class CardInfo { public String getCardNo() { return cardNo; } public void setCardNo(String cardNo) { this.cardNo = cardNo; } @Override public String toString() { return "CardInfo{" + "cardNo=‘" + cardNo + ‘\‘‘ + ‘}‘; } private String cardNo; } }
以上是关于Gson反序列化泛型实例的主要内容,如果未能解决你的问题,请参考以下文章
Android:Gson通过借助TypeToken获取泛型参数的类型的方法