日韩黑丝制服一区视频播放|日韩欧美人妻丝袜视频在线观看|九九影院一级蜜桃|亚洲中文在线导航|青草草视频在线观看|婷婷五月色伊人网站|日本一区二区在线|国产AV一二三四区毛片|正在播放久草视频|亚洲色图精品一区

分享

使用GSON和泛型解析約定格式的JSON串(轉(zhuǎn))

 流浪的星星318 2017-03-25
{"success":true,"data":##} 

success:代表是否訪問成功

    data:后面跟著所需信息.

   

    基本相同的JSON結(jié)構(gòu),所以想定義一種通用模型對(duì)應(yīng)到此結(jié)構(gòu)。但是,data中的數(shù)據(jù)類型不一致。如第一種是簡(jiǎn)單對(duì)象,第二種是對(duì)象中嵌套數(shù)組,第三種是List。針對(duì)data數(shù)據(jù)類型不一致的情況,使用泛型來解決。

復(fù)制代碼
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import com.google.gson.Gson;

public class CommonJson<T> implements Serializable {

    /**
     *
     */
    private static final long serialVersionUID = -3440061414071692254L;

    /**
     * 是否成功
     */
    private Boolean success;

    /**
     * 數(shù)據(jù)
     */
    private T data;

    public Boolean getSuccess() {
        return success;
    }

    public void setSuccess(Boolean success) {
        this.success = success;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }
}
復(fù)制代碼

 GSON對(duì)于泛型的支持不足,為了使GSON對(duì)于泛型進(jìn)行解析,JSON解析與組裝代碼如下:

復(fù)制代碼
       public static CommonJson fromJson(String json, Class clazz) {
        Gson gson = new Gson();
        Type objectType = type(CommonJson.class, clazz);
        return gson.fromJson(json, objectType);
    }

    public String toJson(Class<T> clazz) {
        Gson gson = new Gson();
        Type objectType = type(CommonJson.class, clazz);
        return gson.toJson(this, objectType);
    }

    static ParameterizedType type(final Class raw, final Type... args) {
        return new ParameterizedType() {
            public Type getRawType() {
                return raw;
            }

            public Type[] getActualTypeArguments() {
                return args;
            }

            public Type getOwnerType() {
                return null;
            }
        };
    }
復(fù)制代碼

 以上兩段代碼可以滿足第一種和第二種JSON的解析,對(duì)于第三種,data是List類型的,無法得到List<>的class,所以,針對(duì)第三種格式,實(shí)現(xiàn)代碼如下:

復(fù)制代碼
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

import com.google.gson.Gson;

public class CommonJson4List<T> implements Serializable {

    /**
     *
     */
    private static final long serialVersionUID = -369558847578246550L;

    /**
     * 是否成功
     */
    private Boolean success;

    /**
     * 數(shù)據(jù)
     */
    private List<T> data;

    public Boolean getSuccess() {
        return success;
    }

    public void setSuccess(Boolean success) {
        this.success = success;
    }

    public List<T> getData() {
        return data;
    }

    public void setData(List<T> data) {
        this.data = data;
    }

    public static CommonJson4List fromJson(String json, Class clazz) {
        Gson gson = new Gson();
        Type objectType = type(CommonJson4List.class, clazz);
        return gson.fromJson(json, objectType);
    }

    public String toJson(Class<T> clazz) {
        Gson gson = new Gson();
        Type objectType = type(CommonJson4List.class, clazz);
        return gson.toJson(this, objectType);
    }

    static ParameterizedType type(final Class raw, final Type... args) {
        return new ParameterizedType() {
            public Type getRawType() {
                return raw;
            }

            public Type[] getActualTypeArguments() {
                return args;
            }

            public Type getOwnerType() {
                return null;
            }
        };
    }

}
復(fù)制代碼

測(cè)試代碼如下:

復(fù)制代碼
import java.util.ArrayList;
import java.util.List;

import com.alibaba.asc.sharewood.common.http.CommonJson;
import com.alibaba.asc.sharewood.common.http.CommonJson4List;
import com.alibaba.asc.sharewood.external.service.model.AverageStarLevelAndCount;
import com.alibaba.asc.sharewood.external.service.model.Evalution;
import com.alibaba.asc.sharewood.external.service.model.EvalutionProfile;
import com.alibaba.asc.sharewood.external.service.model.StarLevelStatistics;

public class Test {

    @SuppressWarnings("unchecked")
    public static void main(String[] args) {

        CommonJson<AverageStarLevelAndCount> cj = new CommonJson<AverageStarLevelAndCount>();
        AverageStarLevelAndCount data = new AverageStarLevelAndCount();
        data.setAverageStarLevel(4.7f);
        data.setRemarkCount(10);

        cj.setSuccess(Boolean.TRUE);
        cj.setData(data);

        String res1 = cj.toJson(AverageStarLevelAndCount.class);

        System.out.println(res1);

        CommonJson<AverageStarLevelAndCount> cj2 = CommonJson.fromJson(res1,
                AverageStarLevelAndCount.class);

        System.out.println(cj2.getSuccess());
        System.out.println(cj2.getData().getAverageStarLevel());

        EvalutionProfile p = new EvalutionProfile();
        p.setPage(10);
        p.setPageCount(29);

        StarLevelStatistics s = new StarLevelStatistics();
        s.setStar1(0);
        s.setStar2(10);
        s.setStar3(30);
        s.setStar4(40);
        s.setStar5(20);

        p.setStatistics(s);

        Evalution e1 = new Evalution();

        e1.setStarLevel(4);
        e1.setRemarkTime("2013-02-27 07:21:48");
        e1.setRemarkCotnent("評(píng)價(jià)方未及時(shí)做出評(píng)價(jià),系統(tǒng)默認(rèn)滿意!");
        e1.setTpLogoURL("http://i04.c./cms/upload/2012/186/684/486681_1232736939.png");
        e1.setExplainContent("");
        e1.setPostMemberId("y**f");

        Evalution e2 = new Evalution();

        e2.setStarLevel(4);
        e2.setRemarkTime("2013-02-27 07:21:48");
        e2.setRemarkCotnent("評(píng)價(jià)方未及時(shí)做出評(píng)價(jià),系統(tǒng)默認(rèn)滿意!");
        e2.setTpLogoURL("http://i04.c./cms/upload/2012/186/684/486681_1232736939.png");
        e2.setExplainContent("");
        e2.setPostMemberId("y**f");

        List<Evalution> le = new ArrayList<Evalution>();
        le.add(e1);
        le.add(e2);

        p.setList(le);

        CommonJson<EvalutionProfile> ce = new CommonJson<EvalutionProfile>();

        ce.setSuccess(Boolean.TRUE);
        ce.setData(p);

        String res2 = ce.toJson(EvalutionProfile.class);

        System.out.println(res2);

        String ps = "{\"data\":{\"pageCount\":29,\"page\":\"1\",\"list\":[{\"starLevel\":4,\"remarkTime\":\"2013-04-10 05:17:42\",\"explainTime\":\"\",\"remarkContent\":\"評(píng)價(jià)方未及時(shí)做出評(píng)價(jià),系統(tǒng)默認(rèn)滿意!\",\"tpLogoURL\":\"\",\"explainContent\":\"\",\"postMemberId\":\"b**6\"},{\"starLevel\":4,\"remarkTime\":\"2013-04-05 04:42:40\",\"explainTime\":\"\",\"remarkContent\":\"評(píng)價(jià)方未及時(shí)做出評(píng)價(jià),系統(tǒng)默認(rèn)滿意!\",\"tpLogoURL\":\"\",\"explainContent\":\"\",\"postMemberId\":\"b**8\"},{\"starLevel\":4,\"remarkTime\":\"2013-03-20 00:52:18\",\"explainTime\":\"\",\"remarkContent\":\"評(píng)價(jià)方未及時(shí)做出評(píng)價(jià),系統(tǒng)默認(rèn)滿意!\",\"tpLogoURL\":\"\",\"explainContent\":\"\",\"postMemberId\":\"b**5\"},{\"starLevel\":4,\"remarkTime\":\"2013-03-07 01:51:01\",\"explainTime\":\"\",\"remarkContent\":\"評(píng)價(jià)方未及時(shí)做出評(píng)價(jià),系統(tǒng)默認(rèn)滿意!\",\"tpLogoURL\":\"\",\"explainContent\":\"\",\"postMemberId\":\"b**7\"},{\"starLevel\":4,\"remarkTime\":\"2013-03-06 03:38:57\",\"explainTime\":\"\",\"remarkContent\":\"評(píng)價(jià)方未及時(shí)做出評(píng)價(jià),系統(tǒng)默認(rèn)滿意!\",\"tpLogoURL\":\"\",\"explainContent\":\"\",\"postMemberId\":\"z**2\"},{\"starLevel\":4,\"remarkTime\":\"2013-03-06 03:17:33\",\"explainTime\":\"\",\"remarkContent\":\"評(píng)價(jià)方未及時(shí)做出評(píng)價(jià),系統(tǒng)默認(rèn)滿意!\",\"tpLogoURL\":\"\",\"explainContent\":\"\",\"postMemberId\":\"b**2\"},{\"starLevel\":4,\"remarkTime\":\"2013-03-03 01:40:17\",\"explainTime\":\"\",\"remarkContent\":\"評(píng)價(jià)方未及時(shí)做出評(píng)價(jià),系統(tǒng)默認(rèn)滿意!\",\"tpLogoURL\":\"\",\"explainContent\":\"\",\"postMemberId\":\"a**6\"},{\"starLevel\":4,\"remarkTime\":\"2013-03-01 02:41:31\",\"explainTime\":\"\",\"remarkContent\":\"評(píng)價(jià)方未及時(shí)做出評(píng)價(jià),系統(tǒng)默認(rèn)滿意!\",\"tpLogoURL\":\"\",\"explainContent\":\"\",\"postMemberId\":\"b**4\"},{\"starLevel\":4,\"remarkTime\":\"2013-02-28 03:20:45\",\"explainTime\":\"\",\"remarkContent\":\"評(píng)價(jià)方未及時(shí)做出評(píng)價(jià),系統(tǒng)默認(rèn)滿意!\",\"tpLogoURL\":\"\",\"explainContent\":\"\",\"postMemberId\":\"t**y\"},{\"starLevel\":4,\"remarkTime\":\"2013-02-27 07:21:48\",\"explainTime\":\"\",\"remarkContent\":\"評(píng)價(jià)方未及時(shí)做出評(píng)價(jià),系統(tǒng)默認(rèn)滿意!\","
                + "\"tpLogoURL\":\""
                + "http://i04.c./cms/upload/2012/186/684/486681_1232736939.png\",\"explainContent\":\"\",\"postMemberId\":\"y**f\"}],"
                + "\"statistics\":{\"star5\":59,\"star4\":38,\"star3\":2,\"star2\":1,\"star1\":0}},\"success\":true}";

        CommonJson<EvalutionProfile> re = CommonJson.fromJson(ps,
                EvalutionProfile.class);

        System.out.println(re.getData().getStatistics().getStar5());

        System.out.println(re.getData().getPageCount());

        System.out.println(re.getData().getList().get(0).getPostMemberId());

        CommonJson4List<Evalution> cjl = new CommonJson4List<Evalution>();

        cjl.setSuccess(Boolean.TRUE);
        cjl.setData(le);

        System.out.println("###" + cjl.toJson(Evalution.class));

        String sList = "{\"data\":[{\"starLevel\":4,\"remarkCotnent\":\"評(píng)價(jià)方未及時(shí)做出評(píng)價(jià),系統(tǒng)默認(rèn)滿意!\",\"remarkTime\":\"2013-02-27 07:21:48\",\"explainContent\":\"\",\"postMemberId\":\"y**f\",\"tpLogoURL\":\"http://i04.c./cms/upload/2012/186/684/486681_1232736939.png\"},{\"starLevel\":4,\"remarkCotnent\":\"評(píng)價(jià)方未及時(shí)做出評(píng)價(jià),系統(tǒng)默認(rèn)滿意!\",\"remarkTime\":\"2013-02-27 07:21:48\",\"explainContent\":\"\",\"postMemberId\":\"y**f\",\"tpLogoURL\":\"http://i04.c./cms/upload/2012/186/684/486681_1232736939.png\"}],\"success\":true}";

        CommonJson4List<Evalution> cjle = CommonJson4List.fromJson(sList,
                Evalution.class);

        System.out.println("***"
                + cjle.getData().get(0).getPostMemberId());

    }
}
復(fù)制代碼

執(zhí)行結(jié)果如下:

復(fù)制代碼
{"success":true,"data":{"averageStarLevel":4.7,"remarkCount":10}}
true
4.7
{"success":true,"data":{"page":10,"pageCount":29,"list":[{"starLevel":4,"remarkCotnent":"評(píng)價(jià)方未及時(shí)做出評(píng)價(jià),系統(tǒng)默認(rèn)滿意!","remarkTime":"2013-02-27 07:21:48","explainContent":"","postMemberId":"y**f","tpLogoURL":"http://i04.c./cms/upload/2012/186/684/486681_1232736939.png"},{"starLevel":4,"remarkCotnent":"評(píng)價(jià)方未及時(shí)做出評(píng)價(jià),系統(tǒng)默認(rèn)滿意!","remarkTime":"2013-02-27 07:21:48","explainContent":"","postMemberId":"y**f","tpLogoURL":"http://i04.c./cms/upload/2012/186/684/486681_1232736939.png"}],"statistics":{"star5":20,"star4":40,"star3":30,"star2":10,"star1":0}}}
59
29
b**6
{"success":true,"data":[{"starLevel":4,"remarkCotnent":"評(píng)價(jià)方未及時(shí)做出評(píng)價(jià),系統(tǒng)默認(rèn)滿意!","remarkTime":"2013-02-27 07:21:48","explainContent":"","postMemberId":"y**f","tpLogoURL":"http://i04.c./cms/upload/2012/186/684/486681_1232736939.png"},{"starLevel":4,"remarkCotnent":"評(píng)價(jià)方未及時(shí)做出評(píng)價(jià),系統(tǒng)默認(rèn)滿意!","remarkTime":"2013-02-27 07:21:48","explainContent":"","postMemberId":"y**f","tpLogoURL":"http://i04.c./cms/upload/2012/186/684/486681_1232736939.png"}]}
y**f
復(fù)制代碼

 

Ps:文中說到Gson對(duì)泛型的支持不足,其實(shí)是不正確的,Gson對(duì)泛型做了以下支持:

public static CommonJson4List fromJson(String json, Class clazz) {  
        Gson gson = new Gson();  
        Type objectType = new TypeToken<CommonJson4List<clazz>>() {}.getType();  
        return gson.fromJson(json, objectType);  
    }  

只需將獲取類型的泛型類作為TypeToken的泛型參數(shù)構(gòu)造一個(gè)匿名的子類,就可以通過getType方法獲取一個(gè)parameterized類型,結(jié)果與type方法一致。

    本站是提供個(gè)人知識(shí)管理的網(wǎng)絡(luò)存儲(chǔ)空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點(diǎn)。請(qǐng)注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購買等信息,謹(jǐn)防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請(qǐng)點(diǎn)擊一鍵舉報(bào)。
    轉(zhuǎn)藏 分享 獻(xiàn)花(0

    0條評(píng)論

    發(fā)表

    請(qǐng)遵守用戶 評(píng)論公約

    類似文章 更多