GSON


import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.util.List;
import java.util.Map;

/**
 *    <!--GSON-->
 *         <!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
 *         <dependency>
 *             <groupId>com.google.code.gson</groupId>
 *             <artifactId>gson</artifactId>
 *             <version>2.8.5</version>
 *         </dependency>
 *   GSON工具類
 */

public class utilJSON {
    private static Gson gson = null;

    static {
        if (gson == null) {
            gson = new Gson();
        }
    }

    private String status;
    private Object data;

    public utilJSON(String status, Object data) {
        this.status = status;
        this.data = data;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public Object getObject() {
        return data;
    }

    public void setObject(Object object) {
        this.data = object;
    }

    /**
     * 對象轉json格式
     *
     * @param status 狀態
     * @param object 對象
     * @return
     */
    public static String result(String status, Object object) {
        utilJSON json = new utilJSON(status, object);
        String res = null;
        if (gson != null) {
            res = gson.toJson(json);
        }
        return res;
    }
    /**
     * Json轉成對象
     *
     * @param json
     * @param cls
     * @return 對象
     */
    public static <T> T gsonToBean(String json, Class<T> cls) {
        T t = null;
        if (gson != null) {
            t = gson.fromJson(json, cls);
        }
        return t;
    }
    /**
     * json轉成list中有map的
     *
     * @param json
     * @return List<Map<String, T>>
     */
    public static <T> List<Map<String, T>> gsonToListMaps(String json) {
        List<Map<String, T>> list = null;
        if (gson != null) {
            list = gson.fromJson(json, new TypeToken<List<Map<String, T>>>() {
            }.getType());
        }
        return list;
    }

    /**
     * json轉成map的
     *
     * @param json
     * @return Map<String, T>
     */
    public static <T> Map<String, T> gsonToMaps(String json) {
        Map<String, T> map = null;
        if (gson != null) {
            map = gson.fromJson(json, new TypeToken<Map<String, T>>() {
            }.getType());
        }
        return map;
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM