-2

I'm trying to retrieve certain JSON data from a webserver, which I want to use to display a certain value in an android app. The request is successful (as in, the data is retrieved from the server), but when I want to actually use the JSON, I get the error org.json.JSONObject cannot be converted to JSONArray. The JSON retrieved has the following structure:

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

In this example, 590b14eb66b8f3786317e571 is the ID of the MongoDB document, which can change for every request. So I can't use that to get the required element from the JSON array. The key I'm interested in is "value".

Code to retrieve data:

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;
    }

To then get the actual keys/values required, I'm trying to use this code:

@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();
    }
}

I've already looked through other questions (like this one), but most solutions seem to be build on knowing the name of the root element (which in this example is 590b14eb66b8f3786317e571), however, in my case this name changes every time so I can't reliably use this name. Is there a way to remove the {"590b14eb66b8f3786317e571": } part, and only use the actual included data:

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

Or is there a way to otherwise parse the retrieved string so I can get the value key from the JSON object?

Edit: I've tried two different solutions using iteration, however I still get the same error. The first solution (based on this question):

@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();
                }
            }
        }
    }
}

Second solution, based on this question:

@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();
            }
        }
    }
}

Neither of these solutions fix the problem, so I assume the problems lies in the part before the processFinish method is called.

Community
  • 1
  • 1
Alex
  • 778
  • 3
  • 12
  • 27

2 Answers2

0

Try like this one bro

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);
 }
Ratilal Chopda
  • 4,162
  • 4
  • 18
  • 31
0

It seems like you're trying to cast wrongfully in this lines

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

You know this is a Jsonobject by looking at the json , marked as{} , Jsonarray is marked as [], change it to JSONObject and the rest of the code accordingly , or change the response from the server (if you have access to it), both solutions will work just fine.

yanivtwin
  • 617
  • 8
  • 32