Gson 封裝,json從此很簡單,gsonjson

來源:互聯網
上載者:User

Gson 封裝,json從此很簡單,gsonjson

以前代碼各種 重複,哪裡用到解析了 那裡就寫一遍 gson,各種加班各種苦逼,根本沒理解java的精髓啊。自從開竅之後 開始各種總結 封裝 。用了gson很久了。下面來共用一下我封裝過的 gson吧,如果有用點個贊啊。用到了單利 這樣省點資源。
請各種參考:http://blog.csdn.net/wanghao200906/article/details/45889955

import java.util.List;import java.util.Map;import com.google.gson.Gson;import com.google.gson.reflect.TypeToken;public class GsonUtil {    private static Gson gson = null;    static {        if (gson == null) {            gson = new Gson();        }    }    private GsonUtil() {    }    /**     * 轉成json     *      * @param object     * @return     */    public static String GsonString(Object object) {        String gsonString = null;        if (gson != null) {            gsonString = gson.toJson(object);        }        return gsonString;    }    /**     * 轉成bean     *      * @param gsonString     * @param cls     * @return     */    public static <T> T GsonToBean(String gsonString, Class<T> cls) {        T t = null;        if (gson != null) {            t = gson.fromJson(gsonString, cls);        }        return t;    }    /**     * 轉成list     *      * @param gsonString     * @param cls     * @return     */    public static <T> List<T> GsonToList(String gsonString, Class<T> cls) {        List<T> list = null;        if (gson != null) {            list = gson.fromJson(gsonString, new TypeToken<List<T>>() {            }.getType());        }        return list;    }    /**     * 轉成list中有map的     *      * @param gsonString     * @return     */    public static <T> List<Map<String, T>> GsonToListMaps(String gsonString) {        List<Map<String, T>> list = null;        if (gson != null) {            list = gson.fromJson(gsonString,                    new TypeToken<List<Map<String, T>>>() {                    }.getType());        }        return list;    }    /**     * 轉成map的     *      * @param gsonString     * @return     */    public static <T> Map<String, T> GsonToMaps(String gsonString) {        Map<String, T> map = null;        if (gson != null) {            map = gson.fromJson(gsonString, new TypeToken<Map<String, T>>() {            }.getType());        }        return map;    }

有好的封裝類 記得分享啊

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.