如何使用Volley将这个json数组提取到数组中?

时间:2019-06-11 22:31:36

标签: android json android-volley

json Image我正在尝试从Json Object中提取数据列表(数组),但我不知道。这是我要提取的“成分”的值。我试图将其提取为字符串,但未格式化。我还提供了原始json enter code here的图片。如果我尝试将其提取为“ cake.optJSONArray”,则会收到java.lang.ClassCastException:org.json.JSONArray无法转换为java.util.List 我添加了更多代码来帮助使这个问题更有意义(手指交叉,但我并没有使其更加混乱)。

   try {

                for (int i = 0; i < response.length(); i++) {
                    JSONObject cake = response.getJSONObject(i);

                    String cakeId = cake.optString("id");
                    String cakeName = cake.optString("name");


                    List<Ingredients> ingredients = (List<Ingredients>) cake.optJSONArray("ingredients");

                    mCakeList.add(new CakesItem(cakeId,ingredients, cakeName));
                }

公共类CakesItem {

private String mId;
private List<Ingredients> mIngredients;
private String mName;

public CakesItem(String cakeId, Lists <Ingrediets> ingredients String cakeName) {
    mId = cakeId;
    mIngredients = ingredients;
    mName = cakeName;

}

公共类成分实现Parcelable {

private double quantity;
private String measure, ingredient;


public Ingredients() {
}

1 个答案:

答案 0 :(得分:1)

我不确定您使用的是哪个JSON库,但是如果您导入org.json.JSONArray,那么如果您的蛋糕是从Volley返回的JSONObject响应中得到的org.json.JSONObject,您将使用以下语法:

from PyQt5 import QtWidgets, QtGui

class combo(QtWidgets.QWidget):
    def __init__(self, parent = None):
        super(combo, self).__init__(parent)

        layout = QtWidgets.QHBoxLayout(self)

        self.cb = QtWidgets.QComboBox()
        self.cb.addItems(["1", "2", "3","4"])
        self.cb.setCurrentIndex(2)              # <---
        layout.addWidget(self.cb)

if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)
    ex = combo()
    ex.show()
    sys.exit(app.exec_())

然后,由您决定从JSONArray成分中获取值到列表中。看起来像这样:

JSONObject cake = response.getJSONObject(i);
JSONArray ingredients = cake.getJSONArray("ingredients");