我有一个。我使用内ArrayAdapter为一个列表视图。我需要列表中的项目,并将它们转化为一个JSONArray送到一个API。我已经搜查,但是还没有找到任何解释如何工作的,任何帮助,将不胜感激。

更新的解决方案

这里是什么我做了解决这一问题。

对象。:

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

希望这可以帮助别人有一天!

有帮助吗?

解决方案

如果我正确阅读了JSONArray构造函数,则可以从任何Collection中构建它们(arrayList是Collection的子类),如下所示: 通用标签

参考:

其他提示

使用Gson库将ArrayList转换为JsonArray。 通用标签

正如有人的数字出,运要转换的定义列表 org.json.JSONArray 不是的 com.google.gson.JsonArray正确的 答案应该是这样的:

Gson gson = new Gson();

String listString = gson.toJson(
                    targetList,
           new TypeToken<ArrayList<targetListItem>>() {}.getType());

 JSONArray jsonArray =  new JSONArray(listString);
通用标签

我知道它已经回答了,但是这里有一个更好的解决方案,使用此代码: 通用标签

这样,您可以从类中访问变量,而无需手动键入它们。

更快更好。 希望这可以帮助。

干杯。:D

加入到你的实例:

implementation 'com.squareup.retrofit2:converter-gson:2.3.0'

转换 ArrayListJsonArray

JsonArray jsonElements = (JsonArray) new Gson().toJsonTree(itemsArrayList);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top