转换的ArrayList< MyCustomClass>到JSONArrayLT、ArrayList、MyCustomClass、JSONArray

2023-09-12 06:55:55 作者:风不问归期

我有我的ArrayAdapter中使用一个ListView一个ArrayList。我需要的项目列表中,并将其转换为一个JSONArray要发送到的API。我周围中搜索,但没有发现任何东西,说明如何这可能工作,任何帮助,将AP preciated。

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;
    }
}

下面是我如何将它转换:

Here is how I converted it:

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构造函数,你可以从任何集合构建它们(ArrayList的是收藏的一个子类),如下所示:

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 jsonarray constructor: http://developer.android.com/reference/org/json/JSONArray.html#JSONArray%28java.util.Collection%29 collection: http://developer.android.com/reference/java/util/Collection.html