Gson解析纯Json数组

[
  {
    "type": "123",
    "value": 123
  },
  {
    "type": "234",
    "value": 234
  }
]
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;

public class DataFactory
{
    public static Object getInstanceByJson(Class clazz, String json)
    {
        Object obj = null;
        Gson gson = new Gson();
        obj = gson.fromJson(json, clazz);
        return obj;
    }

    /**
     * @author I321533
     * @param json
     * @param clazz
     * @return
     */
    public static  List jsonToList(String json, Class clazz)
    {
        Gson gson = new Gson();
        T[] array = gson.fromJson(json, clazz);
        return Arrays.asList(array);
    }

    /**
     * @param json
     * @param clazz
     * @return
     */
    public static  ArrayList jsonToArrayList(String json, Class clazz)
    {
        Type type = new TypeToken>()
        {}.getType();
        ArrayList jsonObjects = new Gson().fromJson(json, type);

        ArrayList arrayList = new ArrayList<>();
        for (JsonObject jsonObject : jsonObjects)
        {
            arrayList.add(new Gson().fromJson(jsonObject, clazz));
        }
        return arrayList;
    }
}

你可能感兴趣的:(json)