0

想要遵循 JSON 格式的 Android 代码...有点困惑如何获取数组的值以遵循模式..

{
    "params": [
        {
            "answer_data_all": [
                {
                    "id": "5",
                    "question_id": "14"
                }
            ],
            "form_data_all": [
                {
                    "id": "1",
                    "name": "form 1"
                }
            ]
        }
    ]
}
4

3 回答 3

0

解析 JSON 相当简单。例如,您可以使用Google 的GSON 库。以下是我为您的对象/模型编写的示例:

class MyObject{
    ArrayList<Params> params;

    class Params {
        ArrayList<AnswerData> answer_data_all;
        ArrayList<FormData> form_data_all;

        class AnswerData {
            String id;
            String question_id;
        }

        class FormData {
            String id;
            String name;
        }
    }
}

然后使用以下命令获取对象的实例:

MyObject myObject = (MyObject) (new Gson()).toJson("..json..", MyObject.class);

于 2013-10-09T13:59:13.233 回答
0

你只有一些嵌套JSONArray的 and JSONObject。假设您有此字符串格式的响应,您所要做的就是 JSONObject从该字符串创建,然后提取您需要的内容。正如有人提到的 [ ] 包含JSONArray而 { } 包含JSONObject

JSONObject mainObject = new JSONObject(stringResponse);
JSONArray params = mainObject.getJSONArray("params"); //title of what you want
JSONObject paramsObject = params.getJSONObject(0);
JSONArray answerData = paramsObject.getJSONArray("answer_data_all");
JSONArray formData = paramsObject.getJSONArray("form_data_all");

String id = formData.getJSONObject(0).getString("id");

您应该能够提取所有值做这样的事情。虽然我会说我认为格式很奇怪。您正在使用仅包含其他对象的单个成员数组。使用一个数组来保存所有对象或仅使用单独的 JSONObject 会更有意义。它使它更容易阅读和解析。

于 2013-10-09T14:00:05.397 回答
0
JSONArray feed = feedObject.getJSONArray("params");
    for(int i = 0; i<feed.length(); i++){
        JSONArray tf = feed.getJSONArray(i);
        for (int j = 0; j < tf.length(); j++) {
            JSONObject hy = tf.getJSONObject(j);
            String idt = hy.getString("id");
            String name = hy.getString("name");
        }
    }

**注意:“feedObject”变量是您正在使用的 JSONObject..尽管您的 JSON 提要类型在字符串名称方面有点混合,但现在应该这样做..

于 2013-10-09T14:25:18.193 回答