125

我正在下载一个 JSON 字符串并将其转换为 JSONArray。我把它放到一个列表视图中,以后需要能够从该列表视图中删除,并且由于 JSONArray 没有 .remove 方法(感谢奥巴马),我正在尝试将其转换为数组列表。

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

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

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

4

23 回答 23

191
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));
   } 
} 
于 2013-06-11T05:55:40.597 回答
74

我已经使用Gson(by 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);
    }
}

希望这会帮助你。

于 2015-12-04T05:29:30.650 回答
8

我有快速的解决方案。只需创建一个文件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);
于 2016-12-05T20:49:49.180 回答
7

Instead of converting the JSON string to an ArrayList or even a Map, you can just create a JSONObject itself. This object has the ability to get string values by key, as you want and also to remove objects.

To create a JSONObject from a properly formatted JSON string, you simply call the appropriate constructor.

JSONObject json = new JSONObject(jsonString);
于 2013-06-11T06:07:58.313 回答
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) );
于 2013-06-11T06:03:08.083 回答
5

在 Java 8 中,

IntStream.range(0,jsonArray.length()).mapToObj(i->jsonArray.getString(i)).collect(Collectors.toList())
于 2017-09-18T10:28:51.710 回答
4
 JSONArray array = new JSONArray(json);
 List<JSONObject> list = new ArrayList();
 for (int i = 0; i < array.length();list.add(array.getJSONObject(i++)));
于 2014-12-02T10:17:06.953 回答
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);
于 2013-06-11T06:28:12.067 回答
2

如果你想从 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 类对象列表。

于 2020-04-20T11:01:55.970 回答
2

我有快速的解决方案。只需创建一个文件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);
于 2019-06-20T06:17:49.103 回答
1

使用 GSON 和 Kotlin 你只需要这个:

    val arr = Gson().fromJson(jsonArrayInString, Array<T>::class.java)
于 2021-05-26T09:38:25.790 回答
1

Java 8 风格

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

   List<JSONObject> list = StreamSupport.stream(data.spliterator(), false)
                .map(e -> (JSONObject)e)
                .collect(Collectors.toList());
于 2020-07-14T11:54:15.793 回答
1

只是按照线程的原始主题:

将 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);
于 2020-05-29T17:24:56.320 回答
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;
于 2019-10-11T11:39:20.093 回答
1

如果 Json 对象包含一个字符串数组,那么有一种方法我们甚至不需要使用 JSONArray。

如果 Json 不是字符串格式,我们可以将 json 转换为字符串。现在如果 Json 字符串是:

String value = "[\"value1\",\"value2\"]";

然后我们可以使用获取字符串列表:

List<String> result = new Gson().fromJson(value, List.class);
于 2021-03-11T13:32:49.030 回答
0
public static List<String> convertJsonArrayToStringList(JsonArray ja){
    
    List<String> result = new ArrayList<String>();     
    for(JsonElement je: ja)
        result.add(je.getAsString());
    
    return result;
    
}
于 2021-03-05T01:28:49.813 回答
0

使用 Kotlin,您可以通过使用 MutableList 包装 JSONArray 来避免循环,例如

val artistMetadata = player.metadata.optJSONArray("artist")
val artists = MutableList<String>(artistMetadata.length()) { i -> artistMetadata.getString(i)}
于 2021-02-04T18:54:09.757 回答
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;
}
于 2016-11-09T14:30:50.387 回答
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"));
于 2019-08-06T15:20:59.687 回答
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());
于 2020-08-07T13:14:02.490 回答
0

这可以做到(Java >= 8):

    // Functional (variable)
    Function<JSONArray, ArrayList<String>> convert = jsonArray -> (ArrayList<String>) jsonArray.stream()
        .map(item -> item.toString())
        .collect(Collectors.toList());

    // Call
    convert.apply(jsonArray);


    // Regular method (OOP)
    private Function<JSONArray, ArrayList<String>> convert() {
        return jsonArray -> (ArrayList<String>) jsonArray.stream()
            .map(item -> item.toString())
            .collect(Collectors.toList());
   }

   // Call
   convert().apply(jsonArray);

于 2021-11-20T17:58:14.617 回答
0
ArrayList<String> listdata = new ArrayList<String>();     
JSONArray jArray = (JSONArray)jsonObject; 
if (jArray != null) { 
 listdata.addAll(jArray);
}

@simplified

于 2020-05-21T05:47:31.890 回答
0

我用来将 json 数组转换为 ArrayList 的单行代码,用于存储在名为 classData 的变量中的下面列出的 json 字符串。

List<String> names = new Gson().fromJson(classData.getAsJsonObject("result").getAsJsonArray("names").toString(), new TypeToken<List<String>>(){}.getType());
{   
    "result": {
        "id": "104297",
        "class": "Chemistry",
        "total": 57,
        "names": [
            "Alex",
            "Dan",
            "Rex",
            "Tony",
            "Elizabeth"
        ],
        ...
    }
}
于 2021-05-21T18:36:26.847 回答