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.

UPDATE - SOLUTION

Here is what I ended up doing to solve the issue.

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

And the output:

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

希望有一天这能帮助一些人!

推荐答案

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

参考资料:

Json相关问答推荐

使用JOLT转换来卸载数据

Jolt转换,如果任何字段为空,则将对象值设置为空

与错误相关的未定义&Quot;不是有效的JSON

Oracle plsql:如何将json文件加载到嵌套表中

解析Ansible AWS ec2_security_group中的json以提取安全组ID

使用 TypeScript 接口时如何修复未定义错误?

Golang 解组行为:字段过多?

Serde JSON 反序列化枚举

下一个 Js 部署在 getStaticPath 函数上失败:在 JSON.parse 的位置 0 的 JSON 中出现意外的令牌 < 但在本地运行

在 Flutter 中将对象转换为可编码对象失败

如何使用 boost::json::value 调用无参数函数

如何使用 Swiftui 判断 JSON 是否缺少键值对

SyntaxError:Object.parse(本机)AngularJS中的意外标记o

应该使用什么标头将 GZIP 压缩 JSON 从 Android 客户端发送到服务器?

将错误消息作为 JSON 对象发送

ASP.NET MVC:使用 JsonResult 控制属性名称的序列化

通过 RestAssured 中的 JsonPath 访问匿名数组的元素

JSON.stringify 不会转义?

C#扁平化json struct

PHP json_encode json_decode UTF-8