Convertir un tableau Json en liste Java normale


Existe-t-il un moyen de convertir un tableau JSON en tableau Java normal pour la liaison de données Android ListView?

Author: Sotirios Delimanolis, 2010-08-03

14 answers

ArrayList<String> list = new ArrayList<String>();     
JSONArray jsonArray = (JSONArray)jsonObject; 
if (jsonArray != null) { 
   int len = jsonArray.length();
   for (int i=0;i<len;i++){ 
    list.add(jsonArray.get(i).toString());
   } 
} 
 188
Author: Pentium10, 2012-05-14 04:43:34

Si vous n'avez pas déjà d'objet JSONArray, appelez

JSONArray jsonArray = new JSONArray(jsonArrayString);

Ensuite, parcourez simplement cela, en construisant votre propre tableau. Ce code suppose que c'est un tableau de chaînes, il ne devrait pas être difficile à modifier en fonction de votre structure de tableau particulière.

List<String> list = new ArrayList<String>();
for (int i=0; i<jsonArray.length(); i++) {
    list.add( jsonArray.getString(i) );
}
 59
Author: Nick, 2010-11-13 15:04:19

Au Lieu d'utiliser groupés dans org.json bibliothèque, essayez d'utiliser Jackson ou GSON, où il est un one-liner. Avec Jackson, f. ex:

List<String> list = new ObjectMapper().readValue(json, List.class);
// Or for array:
String[] array = mapper.readValue(json, String[].class);
 14
Author: StaxMan, 2014-12-29 19:28:05

Peut-être que ce n'est qu'une solution de contournement (pas très efficace) mais vous pourriez faire quelque chose comme ceci:

String[] resultingArray = yourJSONarray.join(",").split(",");

Évidemment, vous pouvez changer le séparateur' , ' avec tout ce que vous voulez (j'avais un JSONArray d'adresses e-mail)

 11
Author: Guido Sabatini, 2012-11-22 10:02:28

Utiliser pouvez utiliser un String[] au lieu de ArrayList<String>:

Cela réduira la surcharge de mémoire qu'une ArrayList a

J'espère que ça aide!

String[] stringsArray = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length; i++) {
    parametersArray[i] = parametersJSONArray.getString(i);
}
 4
Author: nurnachman, 2015-07-09 14:19:03

En utilisant Java Streams, vous pouvez simplement utiliser unIntStream mappage des objets:

JSONArray array = new JSONArray(jsonString);
List<String> result = IntStream.range(0, array.length())
        .mapToObj(array::get)
        .map(Object::toString)
        .collect(Collectors.toList());
 3
Author: Samuel Philipp, 2019-07-23 22:22:01

Je sais que cette question concerne JSONArray mais voici un exemple que j'ai trouvé utile où vous n'avez pas besoin d'utiliser JSONArray pour extraire des objets de JSONObject.

import org.json.simple.JSONObject;
import org.json.simple.JSONValue;

String jsonStr = "{\"types\":[1, 2]}";
JSONObject json = (JSONObject) JSONValue.parse(jsonStr);
List<Long> list = (List<Long>) json.get("types");
if (list != null) {
    for (Long s : list) {
        System.out.println(s);
    }
}

Fonctionne également avec un tableau de chaînes

 0
Author: pchot, 2014-07-30 14:27:11

Voici une meilleure façon de le faire: si vous obtenez les données de l'API. Ensuite, ANALYSEZ le JSON et chargez-le sur votre listview:

protected void onPostExecute(String result) {
                Log.v(TAG + " result);


                if (!result.equals("")) {

                    // Set up variables for API Call
                    ArrayList<String> list = new ArrayList<String>();

                    try {
                        JSONArray jsonArray = new JSONArray(result);

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

                            list.add(jsonArray.get(i).toString());

                        }//end for
                    } catch (JSONException e) {
                        Log.e(TAG, "onPostExecute > Try > JSONException => " + e);
                        e.printStackTrace();
                    }


                    adapter = new ArrayAdapter<String>(ListViewData.this, android.R.layout.simple_list_item_1, android.R.id.text1, list);
                    listView.setAdapter(adapter);
                    listView.setOnItemClickListener(new OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                            // ListView Clicked item index
                            int itemPosition = position;

                            // ListView Clicked item value
                            String itemValue = (String) listView.getItemAtPosition(position);

                            // Show Alert
                            Toast.makeText( ListViewData.this, "Position :" + itemPosition + "  ListItem : " + itemValue, Toast.LENGTH_LONG).show();
                        }
                    });

                    adapter.notifyDataSetChanged();


                        adapter.notifyDataSetChanged();

...
 0
Author: Thiago, 2014-12-03 07:19:59

Nous partons de la conversion [ JSONArray - > List ]

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;
}

Ensuite, créez une version générique remplaçant le tableau.getJSONObject (i++) avec POJO

Exemple :

public <T> static List<T> getJSONObjectListFromJSONArray(Class<T> forClass, JSONArray array) 
        throws JSONException {
  ArrayList<Tt> tObjects = new ArrayList<>();
  for (int i = 0; 
           i < (array != null ? array.length() : 0);           
           tObjects.add( (T) createT(forClass, array.getJSONObject(i++))) 
       );
  return tObjects;
}

private static T createT(Class<T> forCLass, JSONObject jObject) {
   // instantiate via reflection / use constructor or whatsoever 
   T tObject = forClass.newInstance(); 
   // if not using constuctor args  fill up 
   // 
   // return new pojo filled object 
   return tObject;
}
 0
Author: ceph3us, 2016-11-09 15:35:06

, Vous pouvez utiliser un String[] au lieu de ArrayList<String>:

J'espère que ça aide!

   private String[] getStringArray(JSONArray jsonArray) throws JSONException {
            if (jsonArray != null) {
                String[] stringsArray = new String[jsonArray.length()];
                for (int i = 0; i < jsonArray.length(); i++) {
                    stringsArray[i] = jsonArray.getString(i);
                }
                return stringsArray;
            } else
                return null;
        }
 0
Author: Iman Marashi, 2017-06-23 06:33:23

   private String[] getStringArray(JSONArray jsonArray) throws JSONException {
            if (jsonArray != null) {
                String[] stringsArray = new String[jsonArray.length()];
                for (int i = 0; i < jsonArray.length(); i++) {
                    stringsArray[i] = jsonArray.getString(i);
                }
                return stringsArray;
            } else
                return null;
        }
 0
Author: user10878560, 2019-01-07 10:21:58

Nous pouvons simplement convertir le JSON en chaîne lisible et le diviser en utilisant la méthode "split" de la classe String.

String jsonAsString = yourJsonArray.toString();
//we need to remove the leading and the ending quotes and square brackets
jsonAsString = jsonAsString.substring(2, jsonAsString.length() -2);
//split wherever the String contains ","
String[] jsonAsStringArray = jsonAsString.split("\",\"");
 0
Author: Mayank Yadav, 2019-01-22 14:26:54

Je sais que la question était pour Java. Mais je veux partager une solution possible pour Kotlin parce que je pense que c'est utile.

Avec Kotlin, vous pouvez écrire une fonction d'extension qui convertit un JSONArray en un tableau natif (Kotlin):

fun JSONArray.asArray(): Array<Any> {
    return Array(this.length()) { this[it] }
}

Maintenant, vous pouvez appeler asArray() directement sur un JSONArray exemple.

 -2
Author: Johannes Barop, 2019-05-21 14:30:32

Que diriez-vous d'utiliser java.util.Les tableaux?

List<String> list = Arrays.asList((String[])jsonArray.toArray())
 -3
Author: Michal Tsadok, 2012-06-25 19:26:00