Java JSONObject getJsonArray空字符串

时间:2018-10-14 06:08:22

标签: java json

我有一些返回的JSON,如下所示:

[{"on_arrival_inst":"Ok","order_inst":"Ok","finished_inst":"Ok"},{"on_arrival_inst":"Arrive","order_inst":"Order","finished_inst":"Finished"}]

我正在尝试将它们分成两个数组,并按如下所示取出字符串:

jsonResultsObject = new JSONObject(result);
            jsonArray = jsonResultsObject.getJSONArray("");

            int count = 0;
            String onArrive, onReady, onFinished;

            while (count<jsonArray.length()){
                JSONObject JO = jsonArray.getJSONObject(count);
                onArrive = JO.getString("on_arrival_inst");
                onReady = JO.getString("order_inst");
                onFinished = JO.getString("finished_inst");

                System.out.println(onArrive);
                System.out.println(onReady);
                System.out.println(onFinished);

                count++;

            }

但是,由于未从JSONObject填充数组,所以代码永远不会进入循环?

2 个答案:

答案 0 :(得分:0)

您的结果是JSONArray而不是JSONObject。这就是为什么必须将其转换为数组而不是对象的原因。

使用

jsonResultsArray = new JSONArray(result);

代替

jsonResultsObject = new JSONObject(result);

,完整的代码将是

        jsonResultsArray = new JSONArray(result);
        int count = 0;
        String onArrive, onReady, onFinished;

        while (count<jsonResultsArray.length()){
            JSONObject JO = jsonResultsArray.getJSONObject(count);
            onArrive = JO.getString("on_arrival_inst");
            onReady = JO.getString("order_inst");
            onFinished = JO.getString("finished_inst");

            System.out.println(onArrive);
            System.out.println(onReady);
            System.out.println(onFinished);

            count++;

        }

答案 1 :(得分:0)

@BigJimmyJones

代码没有进入循环的事实仅仅是因为您的JSONArray没有名为""的键,而是包含了JSONObjects。 JSON中的对象和数组具有不同的注释。参见:JSON Reference Website

因此您的代码应为:

jsonResultsObject = new JSONObject(result);

            String onArrive, onReady, onFinished;

            for (int i=0;i<jsonArray.length();i++){
                JSONObject JO = jsonArray.getJSONObject(i);
                onArrive = JO.getString("on_arrival_inst");
                onReady = JO.getString("order_inst");
                onFinished = JO.getString("finished_inst");

                System.out.println(onArrive);
                System.out.println(onReady);
                System.out.println(onFinished);

            }

还要确保您的代码在try - catch块中以捕获JSONException