gson json 변환 대상 및 대상 대상 변환 json 도움말 클래스

4832 단어 jsongson
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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


public class GsonUtil {
    /** *    */
    private static final Logger LOGGER = LoggerFactory.getLogger(GsonUtil.class);

    /** *      json * * @param value * @return */
    public static String createJsonString(Object value) {
        Gson gson = new Gson();
        String str = gson.toJson(value);
// LOGGER.info("  JSON  !!{}", str);
        return str;
    }

    /** * json       * * @param jsonString * @param cls * @return */
    public static <T> T getPerson(String jsonString, Class<T> clazz) {
        T t = null;
        try {
            Gson gson = new Gson();
            t = gson.fromJson(jsonString, clazz);
        } catch (Exception e) {
            LOGGER.error("JSON       !!{}{}", jsonString, e);
        }
        return t;
    }

    /** * json   List<Object> * @param jsonString * @param cls * @return */
    public static <T> List<T> getPersons(String jsonString, Class<T> clazz) {
        List<T> list = new ArrayList<T>();
        try {
            Gson gson = new Gson();
            list = gson.fromJson(jsonString, new TypeToken<List<T>>() {}.getType());
        } catch (Exception e) {
            LOGGER.error("JSON       !!{}{}", jsonString, e);
        }
        return list;
    }

    /** * json   List<Map<String, Object>> * @param jsonString * @return */
    public static List<Map<String, Object>> listKeyMaps(String jsonString) {
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        try {
            Gson gson = new Gson();
            list = gson.fromJson(jsonString, new TypeToken<List<Map<String, Object>>>() {
            }.getType());
        } catch (Exception e) {
            LOGGER.error("JSON       !!{}{}", jsonString, e);
        }
        return list;
    }

    /** *  Map   Json * * @param map * @return String */
    public static <T> String mapToJson(Map<String, T> map) {
     Gson gson = new Gson();
     String jsonStr = gson.toJson(map);
     return jsonStr;
    }
}

좋은 웹페이지 즐겨찾기