Java问题总结

字节数组相关操作

byte[] --> List<Byte>:Bytes.asList()
List<Byte> --> byte[]:Bytes.toArray()

序列化工具
(1)alibaba

<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>

(2)google

<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>

提供一个基于gson的工具类,供参考

public class GsonUtils {
    private static Gson gson = new Gson();
    private GsonUtils() {}

    /* 转成json */
    public static String BeanToJson(Object object) {
        String gsonString = null;
        if (gson != null) { gsonString = gson.toJson(object); }
        return gsonString;
    }

    /* 转成bean */
    public static <T> T GsonToBean(String gsonString, Class<T> cls) {
        T t = null;
        if (gson != null) { t = gson.fromJson(gsonString, cls); }
        return t;
    }

    /* 转成list  泛型在编译期类型被擦除导致报错 */
    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;
    }

    public static List<Byte> GsonToListForByte(String gsonString) {
        List<Byte> list = null;
        if (gson != null) { list = gson.fromJson(gsonString, new TypeToken<List<Byte>>() { }.getType()); }
        return list;
    }

    /* 转成list  解决泛型问题 */
    public <T> List<T> jsonToList(String json, Class<T> cls) {
        Gson gson = new Gson();
        List<T> list = new ArrayList<T>();
        JsonArray array = new JsonParser().parse(json).getAsJsonArray();
        for (final JsonElement elem : array) { list.add(gson.fromJson(elem, cls)); }
        return list;
    }

    /* 转成list中有map的 */
    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的 */
    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;
    }
}