转换 ArrayList<MyCustomClass>到 JSONArray [英] convert ArrayList<MyCustomClass> to JSONArray
问题描述
我有一个 ArrayList,我在一个 ListView 的 ArrayAdapter 中使用它.我需要获取列表中的项目并将它们转换为 JSONArray 以发送到 API.我已经四处搜索,但没有找到任何解释这可能如何工作的内容,任何帮助将不胜感激.
I have an ArrayList that I use within an ArrayAdapter for a ListView. I need to take the items in the list and convert them to a JSONArray to send to an API. I've searched around, but haven't found anything that explains how this might work, any help would be appreciated.
更新 - 解决方案
这是我最终为解决这个问题所做的.
Here is what I ended up doing to solve the issue.
ArrayList 中的对象:
Object in 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;
}
}
这是我如何转换它:
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());
}
和输出:
[{"Name":"Name 1","Id":0,"Category":"category 1"},{"Name":"Name 2","Id":1,"Category":"category 2"},{"Name":"Name 3","Id":2,"Category":"category 3"}]
希望有一天这对某人有所帮助!
Hope this helps someone some day!
推荐答案
如果我正确阅读了 JSONArray 构造函数,您可以从任何 Collection(arrayList 是 Collection 的子类)构建它们,如下所示:
If I read the JSONArray constructors correctly, you can build them from any Collection (arrayList is a subclass of Collection) like so:
ArrayList<String> list = new ArrayList<String>();
list.add("foo");
list.add("baar");
JSONArray jsArray = new JSONArray(list);
参考文献:
- jsonarray 构造函数:http://developer.android.com/reference/org/json/JSONArray.html#JSONArray%28java.util.Collection%29
- 集合:http://developer.android.com/reference/java/util/Collection.html
这篇关于转换 ArrayList<MyCustomClass>到 JSONArray的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!