Android:org.json.JSONObject无法转换为JSONArray

时间:2017-05-18 12:29:02

标签: android arrays json mongodb

我试图从网络服务器检索某些JSON数据,我想用它来在Android应用中显示某个值。请求成功(例如,从服务器检索数据),但是当我想实际使用JSON时,我收到错误org.json.JSONObject cannot be converted to JSONArray。检索到的JSON具有以下结构:

{
  "590b14eb66b8f3786317e571": {
    "updatedAt": "2017-05-04T11:47:55.000Z",
    "created_at": "2017-05-04T11:47:55.000Z",
    "UId": "590b10981da091b2618a4914",
    "value": 37,
    "_id": "590b14eb66b8f3786317e571",
    "__v": 0
  }
}

在此示例中,590b14eb66b8f3786317e571是MongoDB文档的ID,可以针对每个请求进行更改。所以我无法使用它从JSON数组中获取所需的元素。我感兴趣的关键是"价值"。

检索数据的代码:

private JSONArray getSingleTemperature(URL url) throws IOException, JSONException {
        HttpURLConnection urlConnection = null;
        BufferedReader reader = null;

        String forecastJsonString = null;

        try {
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("GET");
            urlConnection.setRequestProperty("Content-Type", "application/json");
            urlConnection.setRequestProperty("charset", "UTF-8");
            urlConnection.connect();

            InputStream inputStream = urlConnection.getInputStream();
            StringBuffer buffer = new StringBuffer();
            if(inputStream == null) {
                return null;
            }
            reader = new BufferedReader(new InputStreamReader(inputStream));

            String line;
            while((line = reader.readLine()) != null) {
                buffer.append(line + "\n");
            }

            if(buffer.length() == 0) {
                return null;
            }

            forecastJsonString = buffer.toString();
            Log.i("JSON", forecastJsonString);
        } catch(Exception e) {
            e.printStackTrace();
        } finally {
            if(urlConnection != null) {
                urlConnection.disconnect();
            }
            if(reader != null) {
                try {
                    reader.close();
                } catch (final IOException e) {
                    Log.e("PlaceHolderFragment", "Error closing stream", e);
                }
            }
        }

        JSONArray ja = new JSONArray(forecastJsonString);
        return ja;
    }

要获得所需的实际键/值,我尝试使用此代码:

@Override
public void processFinish(JSONArray json) {
    try {
        if(json != null) {
            JSONObject jo = json.getJSONObject(0);
            String temp = jo.getString("value");
            temperature = Integer.parseInt(temp);
            temperatureView.setText(temp + "°C");
            checkTemperature();
        } else {
            buildAlertDialog(getResources().getString(R.string.server_error_title), getResources().getString(R.string.server_error_message));
        }
    } catch(JSONException e) {
        e.printStackTrace();
    }
}

我已经查看了其他问题(例如this一个),但most solutions seem to be build on knowing the name of the root element(在此示例中为590b14eb66b8f3786317e571),但是,在我的情况下,此名称更改每次这样我都无法可靠地使用这个名字。有没有办法删除{"590b14eb66b8f3786317e571": }部分,只使用实际包含的数据:

{
    "updatedAt": "2017-05-04T11:47:55.000Z",
    "created_at": "2017-05-04T11:47:55.000Z",
    "UId": "590b10981da091b2618a4914",
    "value": 37,
    "_id": "590b14eb66b8f3786317e571",
    "__v": 0
}

或者有没有办法解析检索到的string以便我可以从JSON对象中获取value密钥?

编辑:我使用迭代尝试了两种不同的解决方案,但是我仍然得到相同的错误。第一个解决方案(基于this问题):

@Override
public void processFinish(JSONArray json) {
    try {
        if(json != null) {
            JSONObject jo = new JSONObject(json.toString());
            Iterator<?> keys = jo.keys();
            while(keys.hasNext()) {
                String key = (String)keys.next();
                if(jo.get(key) instanceof JSONObject) {
                    String temp = jo.getString("value");
                    temperature = Integer.parseInt(temp);
                    temperatureView.setText(temp + "°C");
                    checkTemperature();
                }
            }
        }
    }
}

第二个解决方案,基于this问题:

@Override
public void processFinish(JSONArray json) {
    try {
        if(json != null) {
            JSONObject jo = new JSONObject(json.toString());
            String temp;
            for(int i = 0; i < json.length(); i++) {
                JSONObject row = json.getJSONObject(i);
                temp = row.getString("value");
                temperature = Integer.parseInt(temp);
                temperatureView.setText(temp + "°C");
                checkTemperature();
            }
        }
    }
}

这些解决方案都没有解决问题,所以我假设问题出在调用processFinish方法之前的部分。

2 个答案:

答案 0 :(得分:0)

尝试这样的兄弟

jObject = new JSONObject(your response);
Iterator<String> keys = jo_jObject.keys();
while (keys.hasNext()) {
String key = keys.next();
                String value = jo_jObject.getString(key);

                Log.v("**********", "**********");
                Log.v("category key", key);
                Log.v("category value", value);
 }

答案 1 :(得分:0)

看起来你正试图在这一行中错误地施展

 JSONArray ja = new JSONArray(forecastJsonString);
 return ja;

你知道这是一个Jsonobject,通过查看json,标记为{},Jsonarray标记为[],相应地将其更改为JSONObject和其余代码,或者更改服务器的响应(如果有的话)访问它), 两种解决方案都可以正常使用。