Pregunta

Tengo un ArrayList que uso dentro de un ArrayAdapter para un ListView.Necesito tomar los elementos de la lista y convertirlos a JSONArray para enviarlos a una API.He buscado por todas partes, pero no he encontrado nada que explique cómo podría funcionar, cualquier ayuda sería apreciada.

ACTUALIZACIÓN - SOLUCIÓN

Esto es lo que terminé haciendo para resolver el problema.

Objeto en ArrayList:

public class ListItem {
    private long _masterId;
    private String _name;
    private long _category;

    public ListItem(long masterId, String name, long category) {
        _masterId = masterId;
        _name = name;
        _category = category;
    }

    public JSONObject getJSONObject() {
        JSONObject obj = new JSONObject();
        try {
            obj.put("Id", _masterId);
            obj.put("Name", _name);
            obj.put("Category", _category);
        } catch (JSONException e) {
            trace("DefaultListItem.toString JSONException: "+e.getMessage());
        }
        return obj;
    }
}

Así es como lo convertí:

ArrayList<ListItem> myCustomList = .... // list filled with objects
JSONArray jsonArray = new JSONArray();
for (int i=0; i < myCustomList.size(); i++) {
        jsonArray.put(myCustomList.get(i).getJSONObject());
}

Y el resultado:

[{"Name":"Name 1","Id":0,"Category":"category 1"},{"Name":"Name 2","Id":1,"Category":"category 2"},{"Name":"Name 3","Id":2,"Category":"category 3"}]

¡Espero que esto ayude a alguien algún día!

¿Fue útil?

Solución

Si leo los constructores JSONArray correctamente, puede crearlos desde cualquier colección (arrayList es una subclase de Collection) así:

ArrayList<String> list = new ArrayList<String>();
list.add("foo");
list.add("baar");
JSONArray jsArray = new JSONArray(list);

Referencias:

Otros consejos

Utilice la biblioteca Gson para convertir ArrayList a JsonArray.

Gson gson = new GsonBuilder().create();
JsonArray myCustomArray = gson.toJsonTree(myCustomList).getAsJsonArray();

Cuando alguien se da cuenta de que el OP quiere convertir la lista personalizada en org.json.JSONArray, no en com.google.gson.JsonArray, la respuesta CORRECTA debería ser así:

Gson gson = new Gson();

String listString = gson.toJson(
                    targetList,
           new TypeToken<ArrayList<targetListItem>>() {}.getType());

 JSONArray jsonArray =  new JSONArray(listString);
public void itemListToJsonConvert(ArrayList<HashMap<String, String>> list) {

        JSONObject jResult = new JSONObject();// main object
        JSONArray jArray = new JSONArray();// /ItemDetail jsonArray

        for (int i = 0; i < list.size(); i++) {
            JSONObject jGroup = new JSONObject();// /sub Object

            try {
                jGroup.put("ItemMasterID", list.get(i).get("ItemMasterID"));
                jGroup.put("ID", list.get(i).get("id"));
                jGroup.put("Name", list.get(i).get("name"));
                jGroup.put("Category", list.get(i).get("category"));

                jArray.put(jGroup);

                // /itemDetail Name is JsonArray Name
                jResult.put("itemDetail", jArray);
                return jResult;
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

    }

Sé que ya está respondido, pero hay una mejor solución aquí, use este código:

for ( Field f : context.getFields() ) {
     if ( f.getType() == String.class ) || ( f.getType() == String.class ) ) {
           //DO String To JSON
     }
     /// And so on...
}

De esta manera puede acceder a las variables de la clase sin escribirlas manualmente ..

Más rápido y mejor ... Espero que esto ayude.

Saludos.: D

Agregar a su gradle:

implementation 'com.squareup.retrofit2:converter-gson:2.3.0'

Convertir ArrayList en JsonArray

JsonArray jsonElements = (JsonArray) new Gson().toJsonTree(itemsArrayList);
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top