Existe-t-il un moyen de convertir JSON Array en Java Array normal pour la liaison de données Android ListView?
Existe-t-il un moyen de convertir JSON Array en Java Array normal pour la liaison de données Android ListView?
Réponses:
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());
}
}
jsonArray.get(i)
retourne null (suite à l'analyse de this :) [ "String 1", null, "String 2" ]
? Votre boucle for ne planterait-elle pas alors?
size()
place de length()
.
Si vous ne disposez pas déjà d'un objet JSONArray, appelez
JSONArray jsonArray = new JSONArray(jsonArrayString);
Ensuite, parcourez simplement cela, en construisant votre propre tableau. Ce code suppose qu'il s'agit d'un tableau de chaînes, il ne devrait pas être difficile à modifier pour s'adapter à 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 une org.json
bibliothèque intégrée, essayez d'utiliser Jackson ou GSON, où il s'agit d'une ligne unique. Avec Jackson, par exemple:
List<String> list = new ObjectMapper().readValue(json, List.class);
// Or for array:
String[] array = mapper.readValue(json, String[].class);
Ce n'est peut-être qu'une solution de contournement (pas très efficace) mais vous pouvez 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 plusieurs JSONArray
adresses e-mail)
L'utilisation peut utiliser un String[]
au lieu d'un ArrayList<String>
:
Cela réduira la surcharge de mémoire d'un ArrayList
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 un IntStream
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 l'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, PARSEZ le JSON et chargez-le dans votre liste:
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 <JSONObject>]
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;
}
créer ensuite une version générique en remplaçant array.getJSONObject (i ++) par 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 d'un 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 Kotlin
car je pense que c'est utile.
Avec Kotlin, vous pouvez écrire une fonction d'extension qui convertit a JSONArray
en un tableau natif (Kotlin):
fun JSONArray.asArray(): Array<Any> {
return Array(this.length()) { this[it] }
}
Vous pouvez désormais appeler asArray()
directement une JSONArray
instance.
Que diriez-vous d'utiliser java.util.Arrays?
List<String> list = Arrays.asList((String[])jsonArray.toArray())
toArray()
méthode dans la JSONArray()
documentation. json.org/javadoc/org/json/JSONArray.html Cette question n'aurait probablement pas été posée s'il y avait un simple toArray()
.
org.JSONArray
utilise une ArrayList sous le capot ...The arrayList where the JSONArray's properties are kept
, donc la plupart des boucles se font pour rien dans de nombreux cas (juste pour l'encapsulation)