php json 转arraylist,转换ArrayList 到JSONArray

我有一个ArrayList,可在ArrayAdapter中用于ListView。我需要将列表中的项目转换为JSONArray才能发送到API。我四处搜寻,但没有找到任何说明其工作方式的信息,我们将不胜感激。

更新-解决方案

这就是我最终要解决的问题。

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 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"}]

希望有一天能对某人有所帮助!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值