ListView için bir ArrayAdapter içinde kullandığım bir ArrayList var. Bir API'ye göndermek için listedeki öğeleri alıp bir JSONArray'e dönüştürmem gerekiyor. Etrafı araştırdım, ancak bunun nasıl çalıştığını açıklayan hiçbir şey bulamadım, herhangi bir yardım takdir edilecektir.
GÜNCELLEME - ÇÖZÜM
İşte sorunu çözmek için yaptığım şey.
ArrayList'teki nesne:
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;
}
}
İşte onu nasıl dönüştürdüm:
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());
}
Ve çıktı:
[{"Name":"Name 1","Id":0,"Category":"category 1"},{"Name":"Name 2","Id":1,"Category":"category 2"},{"Name":"Name 3","Id":2,"Category":"category 3"}]
Umarım bu bir gün birine yardımcı olur!