操作json的工具类


package com.jiao.luo.utils;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class GsonTools {

    public GsonTools() {
        // TODO Auto-generated constructor stub
    }

    /**
     * 实体转换成json字符串
     *
     * @param object
     * @return
     */
    public static String createGsonString(Object object) {
        Gson gson = new Gson();
        String gsonString = gson.toJson(object);
        return gsonString;
    }

    /**
     * json转实体
     *
     * @param gsonString
     * @param cls
     * @param 
     * @return
     */
    public static  T changeGsonToBean(String gsonString, Class cls) {
        Gson gson = new Gson();
        T t = gson.fromJson(gsonString, cls);
        return t;
    }

    //json转成List数组
    public static  List changeGsonToList(String gsonString, Class cls) {
        Gson gson = new Gson();
        List list = new ArrayList();
        JsonArray array = new JsonParser().parse(gsonString).getAsJsonArray();
        for (final JsonElement elem : array) {
            list.add(gson.fromJson(elem, cls));
        }
        return list;
    }


    public static  List> changeGsonToListMaps(
            String gsonString) {
        List> list = null;
        Gson gson = new Gson();
        list = gson.fromJson(gsonString, new TypeToken>>() {
        }.getType());
        return list;
    }

    public static  Map changeGsonToMaps(String gsonString) {
        Map map = null;
        Gson gson = new Gson();
        map = gson.fromJson(gsonString, new TypeToken>() {
        }.getType());
        return map;
    }
}

你可能感兴趣的:(工具类,java,android,json)