将JSONarray转换为ArrayList


104

我正在下载JSON字符串并将其转换为JSONArray。我将其放入列表视图,以后需要从该列表视图中删除,并且由于JSONArray没有.remove方法(感谢Obama),因此我尝试将其转换为arraylist。

这是我的JSON(array.toString()):

[{"thumb_url":"tb-1370913834.jpg","event_id":"15","count":"44","event_tagline":"this is a tagline","event_name":"5th birthday","event_end":"1370919600","event_start":"1370876400"}]

我需要将其放入数组,并能够通过它们各自的键来调用字符串。感谢任何帮助!


当您说出按键时,这是否意味着某种字典(Android中的Map)?数组将基于索引。查看developer.android.com/reference/java/util/Map.html,了解如何创建和使用。
brianestey

可以使用地图使用自定义baseadapter填充列表视图吗?我宁愿不使用索引,以防JSON更改顺序。
TheGeekNess 2013年

ListView将按索引从适配器中获取对象,因此无论如何您都需要以某种顺序维护列表。如果您想保持键的顺序(并知道编译时键的含义),则可以按照自己喜欢的顺序对这些键的数组进行硬编码,并在从地图中获取时进行排序。
brianestey

Answers:


164
ArrayList<String> listdata = new ArrayList<String>();     
JSONArray jArray = (JSONArray)jsonObject; 
if (jArray != null) { 
   for (int i=0;i<jArray.length();i++){ 
    listdata.add(jArray.getString(i));
   } 
} 

3
并且listdata.add(jArray.optJSONObject(i));如果您的listdata是JSONObject arrayList。ArrayList<JSONObject> listdata = new ArrayList<JSONObject>();
Subin Sebastian 2014年

2
好的摘要。以防万一,如果有人愿意:在github gist.github.com/codebutler/2339666
inexcii 2014年

2
为什么不使用ArrayList<Object>
natanavra 2015年

我如何处理Json数组为空。请给我答复
MohanRaj S

3
还有其他方法可以不循环吗?
K.Sopheak

64

我已经使用Gson(由Google完成)

将以下行添加到模块的中build.gradle

dependencies {
  // ...
  // Note that `compile` will be deprecated. Use `implementation` instead.
  // See https://stackoverflow.com/a/44409111 for more info
  implementation 'com.google.code.gson:gson:2.8.2'
}

JSON 串:

private String jsonString = "[\n" +
            "        {\n" +
            "                \"id\": \"c200\",\n" +
            "                \"name\": \"Ravi Tamada\",\n" +
            "                \"email\": \"ravi@gmail.com\",\n" +
            "                \"address\": \"xx-xx-xxxx,x - street, x - country\",\n" +
            "                \"gender\" : \"male\",\n" +
            "                \"phone\": {\n" +
            "                    \"mobile\": \"+91 0000000000\",\n" +
            "                    \"home\": \"00 000000\",\n" +
            "                    \"office\": \"00 000000\"\n" +
            "                }\n" +
            "        },\n" +
            "        {\n" +
            "                \"id\": \"c201\",\n" +
            "                \"name\": \"Johnny Depp\",\n" +
            "                \"email\": \"johnny_depp@gmail.com\",\n" +
            "                \"address\": \"xx-xx-xxxx,x - street, x - country\",\n" +
            "                \"gender\" : \"male\",\n" +
            "                \"phone\": {\n" +
            "                    \"mobile\": \"+91 0000000000\",\n" +
            "                    \"home\": \"00 000000\",\n" +
            "                    \"office\": \"00 000000\"\n" +
            "                }\n" +
            "        },\n" +
            "        {\n" +
            "                \"id\": \"c202\",\n" +
            "                \"name\": \"Leonardo Dicaprio\",\n" +
            "                \"email\": \"leonardo_dicaprio@gmail.com\",\n" +
            "                \"address\": \"xx-xx-xxxx,x - street, x - country\",\n" +
            "                \"gender\" : \"male\",\n" +
            "                \"phone\": {\n" +
            "                    \"mobile\": \"+91 0000000000\",\n" +
            "                    \"home\": \"00 000000\",\n" +
            "                    \"office\": \"00 000000\"\n" +
            "                }\n" +
            "        },\n" +
            "        {\n" +
            "                \"id\": \"c203\",\n" +
            "                \"name\": \"John Wayne\",\n" +
            "                \"email\": \"john_wayne@gmail.com\",\n" +
            "                \"address\": \"xx-xx-xxxx,x - street, x - country\",\n" +
            "                \"gender\" : \"male\",\n" +
            "                \"phone\": {\n" +
            "                    \"mobile\": \"+91 0000000000\",\n" +
            "                    \"home\": \"00 000000\",\n" +
            "                    \"office\": \"00 000000\"\n" +
            "                }\n" +
            "        },\n" +
            "        {\n" +
            "                \"id\": \"c204\",\n" +
            "                \"name\": \"Angelina Jolie\",\n" +
            "                \"email\": \"angelina_jolie@gmail.com\",\n" +
            "                \"address\": \"xx-xx-xxxx,x - street, x - country\",\n" +
            "                \"gender\" : \"female\",\n" +
            "                \"phone\": {\n" +
            "                    \"mobile\": \"+91 0000000000\",\n" +
            "                    \"home\": \"00 000000\",\n" +
            "                    \"office\": \"00 000000\"\n" +
            "                }\n" +
            "        },\n" +
            "        {\n" +
            "                \"id\": \"c205\",\n" +
            "                \"name\": \"Dido\",\n" +
            "                \"email\": \"dido@gmail.com\",\n" +
            "                \"address\": \"xx-xx-xxxx,x - street, x - country\",\n" +
            "                \"gender\" : \"female\",\n" +
            "                \"phone\": {\n" +
            "                    \"mobile\": \"+91 0000000000\",\n" +
            "                    \"home\": \"00 000000\",\n" +
            "                    \"office\": \"00 000000\"\n" +
            "                }\n" +
            "        },\n" +
            "        {\n" +
            "                \"id\": \"c206\",\n" +
            "                \"name\": \"Adele\",\n" +
            "                \"email\": \"adele@gmail.com\",\n" +
            "                \"address\": \"xx-xx-xxxx,x - street, x - country\",\n" +
            "                \"gender\" : \"female\",\n" +
            "                \"phone\": {\n" +
            "                    \"mobile\": \"+91 0000000000\",\n" +
            "                    \"home\": \"00 000000\",\n" +
            "                    \"office\": \"00 000000\"\n" +
            "                }\n" +
            "        },\n" +
            "        {\n" +
            "                \"id\": \"c207\",\n" +
            "                \"name\": \"Hugh Jackman\",\n" +
            "                \"email\": \"hugh_jackman@gmail.com\",\n" +
            "                \"address\": \"xx-xx-xxxx,x - street, x - country\",\n" +
            "                \"gender\" : \"male\",\n" +
            "                \"phone\": {\n" +
            "                    \"mobile\": \"+91 0000000000\",\n" +
            "                    \"home\": \"00 000000\",\n" +
            "                    \"office\": \"00 000000\"\n" +
            "                }\n" +
            "        },\n" +
            "        {\n" +
            "                \"id\": \"c208\",\n" +
            "                \"name\": \"Will Smith\",\n" +
            "                \"email\": \"will_smith@gmail.com\",\n" +
            "                \"address\": \"xx-xx-xxxx,x - street, x - country\",\n" +
            "                \"gender\" : \"male\",\n" +
            "                \"phone\": {\n" +
            "                    \"mobile\": \"+91 0000000000\",\n" +
            "                    \"home\": \"00 000000\",\n" +
            "                    \"office\": \"00 000000\"\n" +
            "                }\n" +
            "        },\n" +
            "        {\n" +
            "                \"id\": \"c209\",\n" +
            "                \"name\": \"Clint Eastwood\",\n" +
            "                \"email\": \"clint_eastwood@gmail.com\",\n" +
            "                \"address\": \"xx-xx-xxxx,x - street, x - country\",\n" +
            "                \"gender\" : \"male\",\n" +
            "                \"phone\": {\n" +
            "                    \"mobile\": \"+91 0000000000\",\n" +
            "                    \"home\": \"00 000000\",\n" +
            "                    \"office\": \"00 000000\"\n" +
            "                }\n" +
            "        },\n" +
            "        {\n" +
            "                \"id\": \"c2010\",\n" +
            "                \"name\": \"Barack Obama\",\n" +
            "                \"email\": \"barack_obama@gmail.com\",\n" +
            "                \"address\": \"xx-xx-xxxx,x - street, x - country\",\n" +
            "                \"gender\" : \"male\",\n" +
            "                \"phone\": {\n" +
            "                    \"mobile\": \"+91 0000000000\",\n" +
            "                    \"home\": \"00 000000\",\n" +
            "                    \"office\": \"00 000000\"\n" +
            "                }\n" +
            "        },\n" +
            "        {\n" +
            "                \"id\": \"c2011\",\n" +
            "                \"name\": \"Kate Winslet\",\n" +
            "                \"email\": \"kate_winslet@gmail.com\",\n" +
            "                \"address\": \"xx-xx-xxxx,x - street, x - country\",\n" +
            "                \"gender\" : \"female\",\n" +
            "                \"phone\": {\n" +
            "                    \"mobile\": \"+91 0000000000\",\n" +
            "                    \"home\": \"00 000000\",\n" +
            "                    \"office\": \"00 000000\"\n" +
            "                }\n" +
            "        },\n" +
            "        {\n" +
            "                \"id\": \"c2012\",\n" +
            "                \"name\": \"Eminem\",\n" +
            "                \"email\": \"eminem@gmail.com\",\n" +
            "                \"address\": \"xx-xx-xxxx,x - street, x - country\",\n" +
            "                \"gender\" : \"male\",\n" +
            "                \"phone\": {\n" +
            "                    \"mobile\": \"+91 0000000000\",\n" +
            "                    \"home\": \"00 000000\",\n" +
            "                    \"office\": \"00 000000\"\n" +
            "                }\n" +
            "        }\n" +
            "    ]";

ContactModel.java

public class ContactModel {
     public String id;
     public String name;
     public String email;
}

用于将JSON字符串转换为的代码ArrayList<Model>

注意:您必须导入java.lang.reflect.Type;

// Top of file
import java.lang.reflect.Type;

// ...

private void parseJSON() {
    Gson gson = new Gson();
    Type type = new TypeToken<List<ContactModel>>(){}.getType();
    List<ContactModel> contactList = gson.fromJson(jsonString, type);
    for (ContactModel contact : contactList){
        Log.i("Contact Details", contact.id + "-" + contact.name + "-" + contact.email);
    }
}

希望这会帮助你。


4
三行...完成!我认为这应该是一个可以接受的答案,因为(a)只有三行代码可以很好地工作,并且(b)几乎没有答案实际上执行从JSONArray到List <CustomObject>的类型化转换。谢谢!
约翰·沃德

它必须是JSONArray,JSONElement似乎不起作用。因此,应使用此getAsJsonArray()方法。谢谢!
嘉恒陶

1
正是我需要的,谢谢!注意:您必须导入以下内容:java.lang.reflect.Type; com.google.gson.reflect.TypeToken;
Chandrani H

太棒了,这应该是公认的答案!。谢谢
Yeuni

这说不出typetoken的init受保护,这行不通
nikoss

7

尝试这种方式只需循环遍历,即可构建自己的数组。该代码假定它是一个字符串数组,不难修改以适合您的特定数组结构。

JSONArray jsonArray = new JSONArray(jsonArrayString);
List<String> list = new ArrayList<String>();
for (int i=0; i<jsonArray.length(); i++) {
    list.add( jsonArray.getString(i) );

6

无需将JSON字符串转换为ArrayList或什至Map,您只需创建一个JSONObject本身即可。该对象可以根据需要通过键获取字符串值,也可以删除对象

要从JSONObject格式正确的JSON字符串创建一个,只需调用适当的构造函数

JSONObject json = new JSONObject(jsonString);

1
我对此解决方案特别遇到的问题是,当处理JSONObject和JSONArray时,它们会抛出JSONException。有时,将JSONArray的内容传递给不需要知道JSON的函数很方便。
亚伦·多尔蒂

2
我同意。我会将JSONObject用作将JSON文本解析为可用模型对象的一部分。引发的任何JSONException都将指示源JSON有问题,这意味着您无法将其解析为JSONArray或JSONObject,更不用说其他模型对象了。
brianestey 2015年

6

我有快速的解决方案。只需创建一个文件ArrayUtil.java

import java.util.ArrayList;
import java.util.Collection;
import org.json.JSONArray;
import org.json.JSONException;

public class ArrayUtil
{
    public static ArrayList<Object> convert(JSONArray jArr)
    {
        ArrayList<Object> list = new ArrayList<Object>();
        try {
            for (int i=0, l=jArr.length(); i<l; i++){
                 list.add(jArr.get(i));
            }
        } catch (JSONException e) {}

        return list;
    }

    public static JSONArray convert(Collection<Object> list)
    {
        return new JSONArray(list);
    }

}

用法:

ArrayList<Object> list = ArrayUtil.convert(jArray);

要么

JSONArray jArr = ArrayUtil.convert(list);

我该怎么办,如果需要返回一个ArrayList<String>

我认为无法将ArrayList <Object>
强制转换

1
对此答案表示敬意。你解决了我的一天!我花了2个小时来解决这个问题。其实我的问题是我想要把转换JSONArray到一个列表,以便我可以把ListHashMap,所以此util的工作对我来说相当不错。感谢@Vasilii Suricov
Jose Mhlanga

5

在Java 8中,

IntStream.range(0,jsonArray.length()).mapToObj(i->jsonArray.getString(i)).collect(Collectors.toList())

1
唯一的问题是JSONArray.getString(...)引发了一个异常,该异常必须在映射内部进行处理,因此您最终将遇到的异常List<String> listOfStrings = IntStream.range(0, array.length()).mapToObj(i -> { try { return array.getString(i); } catch (JSONException e) { throw new AssertionFailedError("JSONArray is not a list of Strings! " + e.getMessage()); } }).collect(Collectors.toList());不再那么优雅。因此,我将继续学习:)
LazR

这是最好的答案(恕我直言),但是如果有一种方法不需要多次访问jsonArray引用,那将是一个很好的选择。
djangofan

4
 JSONArray array = new JSONArray(json);
 List<JSONObject> list = new ArrayList();
 for (int i = 0; i < array.length();list.add(array.getJSONObject(i++)));

2

为方便起见,请使用POJO。

尝试这样..

List<YourPojoObject> yourPojos = new ArrayList<YourPojoObject>();

JSONObject jsonObject = new JSONObject(jsonString);
YourPojoObject yourPojo = new YourPojoObject();
yourPojo.setId(jsonObject.getString("idName"));
...
...

yourPojos.add(yourPojo);

1

使用Gson

    List<Student> students = new ArrayList<>();
    JSONArray jsonArray = new JSONArray(stringJsonContainArray);
    for (int i = 0; i < jsonArray.length(); i++) {
        Student student = new Gson().fromJson(jsonArray.get(i).toString(), Student.class);
        students.add(student);
    }
    return students;

1

如果要从JSON字符串数组提取数据,这是我的工作代码。更改参数作为您的数据。


PoJo课

public class AllAppModel {
    private String appName;
    private String packageName;
    private int uid;
    private boolean isSelected;
    private boolean isSystemApp;
    private boolean isFav;
}

使用下面的代码行提取数据

try {
    JSONArray jsonArr = new JSONArray("Your json string array");
    List<AllAppModel> lstExtrextData = new ArrayList<>();
    for (int i = 0; i < jsonArr.length(); i++) {
        JSONObject jsonObj = jsonArr.getJSONObject(i);
        AllAppModel data = new AllAppModel();
        data.setAppName(jsonObj.getString("appName"));
        data.setPackageName(jsonObj.getString("packageName"));
        data.setUid(jsonObj.getInt("uid"));
        data.setSelected(jsonObj.getBoolean("isSelected"));
        data.setSystemApp(jsonObj.getBoolean("isSystemApp"));
        data.setFav(jsonObj.getBoolean("isFav"));
        lstExtrextData.add(data);
    }
} catch (JSONException e) {
    e.printStackTrace();
}

它将返回您PoJo类对象的列表。


1

Java 8样式

   JSONArray data = jsonObject.getJSONArray("some-node");

   List<JSONObject> list = StreamSupport.stream(data.spliterator(), false)
                .map(e -> (JSONObject)e)
                .collect(Collectors.toList());

0
public static List<JSONObject> getJSONObjectListFromJSONArray(JSONArray array) 
        throws JSONException {
  ArrayList<JSONObject> jsonObjects = new ArrayList<>();
  for (int i = 0; 
           i < (array != null ? array.length() : 0);           
           jsonObjects.add(array.getJSONObject(i++))
       );
  return jsonObjects;
}

0

我有快速的解决方案。只需创建一个文件ArrayUtil.java

ObjectMapper mapper = new ObjectMapper(); 
List<Student> list = Arrays.asList(mapper.readValue(jsonString, Student[].class));

用法:

ArrayList<Object> list = ArrayUtil.convert(jArray);

要么

JSONArray jArr = ArrayUtil.convert(list);

0

通用变体

public static <T> List<T> getList(JSONArray jsonArray) throws Exception {

    List<T> list = new ArrayList<>(jsonArray.length());

    for (int i = 0; i < jsonArray.length(); i++) {

        list.add((T)jsonArray.get(i));
    }

    return list;

}

//Usage

List<String> listKeyString = getList(dataJsonObject.getJSONArray("keyString"));

0
ArrayList<String> listdata = new ArrayList<String>();     
JSONArray jArray = (JSONArray)jsonObject; 
if (jArray != null) { 
 listdata.addAll(jArray);
}

@简体


0

只是按照线程的原始主题进行操作:

将jsonarray转换为列表(此处使用jackson jsonarray和对象映射器):

ObjectMapper mapper = new ObjectMapper();
JSONArray array = new JSONArray();
array.put("IND");
array.put("CHN");
List<String> list = mapper.readValue(array.toString(), List.class);

0

一个更简单的Java 8替代方案:

JSONArray data = new JSONArray(); //create data from this -> [{"thumb_url":"tb-1370913834.jpg","event_id":...}]

List<JSONObject> list = data.stream().map(o -> (JSONObject) o).collect(Collectors.toList());
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.