Converting ArrayList to JSONArray

后端 未结 1 752
迷失自我
迷失自我 2021-01-29 11:16

I am using ArrayList> to store my cart items. But I need to convert it to JSONArray to send it to the database. But

相关标签:
1条回答
  • 2021-01-29 11:36

    I found this to be helpful in my project:

    Object in my 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;
        }
    }
    

    The actual conversion:

    ArrayList<ListItem> myCustomList = ArrayList<ListItem>();
    JSONArray jsonArray = new JSONArray();
    for (int i=0; i < myCustomList.size(); i++) {
            jsonArray.put(myCustomList.get(i).getJSONObject());
    }
    
    0 讨论(0)
提交回复
热议问题