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?
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());
}
}
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) );
}
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);
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)
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);
}
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());
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
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();
...
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;
}
, 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;
}
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;
}
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("\",\"");
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.
Que diriez-vous d'utiliser java.util.Les tableaux?
List<String> list = Arrays.asList((String[])jsonArray.toArray())