package com.xuqm.base.common;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created by xuqm on 2016/6/3.
 */
public class GsonImplHelp extends Json {
    private Gson gson = new Gson();

    @Override
    public String toJson(Object src) {
        return gson.toJson(src);

    }

    @Override
    public <T> T toObject(String json, Class<T> claxx) {
        return gson.fromJson(json, claxx);

    }

    @Override
    public <T> T toObject(byte[] bytes, Class<T> claxx) {
        return gson.fromJson(new String(bytes), claxx);

    }

    public <T> List<T> toList(String json, Class<T> clazz) {
        JsonArray jsonArray = new JsonParser().parse(json).getAsJsonArray();

        List<T> list = new ArrayList<>();
        for (JsonElement jsonElement : jsonArray) {
            list.add(gson.fromJson(jsonElement, clazz)); //cls
        }

        return list;


    }

    public static <T> List<T> stringToArray(String s, Class<T[]> cls) {
        T[] array = new Gson().fromJson(s, cls);
        return Arrays.asList(array);
    }

}
