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;
    }
}

 

posted @ 2017-12-04 17:38  zslm___  阅读(3596)  评论(1编辑  收藏  举报