json数组转成ArrayList

来源:互联网 发布:手机淘宝旧版本5.8 编辑:程序博客网 时间:2024/06/06 01:24

问题:

1、json转成ArrayList

解决办法:

1、用gson转;

2、导入gson-2.2.4-javadoc.jar、gson-2.2.4-sources.jar、gson-2.2.4.jar

3、添加函数:


public static <T> ArrayList<T> jsonToArrayList(String json, Class<T> clazz){    Type type = new TypeToken<ArrayList<JsonObject>>(){}.getType();    ArrayList<JsonObject> jsonObjects = new Gson().fromJson(json, type);    ArrayList<T> arrayList = new ArrayList<T>();    for (JsonObject jsonObject : jsonObjects)    {        arrayList.add(new Gson().fromJson(jsonObject, clazz));    }    return arrayList;}----------

4、例子:

注意:1、arrayList中的对象是JsonObject对象     2、JsonObject与JSONObject的区别,前者是com.google.gson.JsonObject,后者是org.json.JSONObject
  ArrayList arrayList=Apis.jsonToArrayList(json, JsonObject.class);  for(int i=0;i<arrayList.size();i++){  JsonObject  jsonObject=(JsonObject)arrayList.get(i);  String id=String.valueOf(jsonObject.get("id"));  .......

5、如何将一个String字符串转换为JSONObject:
例子:

{"coorX":29.1312,"coorY":20.1262,"mapId":1,"type":"AbsoluteLocation"}JSONObject jsonObject_location = new JSONObject(json字符串变量);