Estoy tratando de extraer claves y valores de mi JSONObject. Pero no soy capaz de hacer eso. Aquí está el JSON:
[{"id":["5"]},{"Tech":["Java"]}]Es una cadena inicialmente. He convertido eso a JSONObject usando:
JSONObject jsonObj = new JSONObject("[{"id":["5"]},{"Tech":["Java"]}]");Entonces estoy tratando de obtener la clave y el valor por:
jsonObj.getString("id");Pero me está dando nulo. ¿Puede alguien ayudarme aquí?
Prueba esto:
try { JSONArray jsonArr = new JSONArray("[{\"id\":[\"5\"]},{\"Tech\":[\"Java\"]}]"); for (int i = 0; i < jsonArr.length(); i++) { JSONObject jsonObj = jsonArr.getJSONObject(i); String k = jsonObj.keys().next(); Log.i("Info", "Key: " + k + ", value: " + jsonObj.getString(k)); } } catch (JSONException ex) { ex.printStackTrace(); }El parámetro que está enviando es JsonArray y se refiere a JsonObject. La forma correcta es
JSONObject jsonObj = new JSONObject("{'id':['5','6']},{'Tech':['Java']}"); System.out.println(jsonObj.getString("id")); JSONArray jsonArray = new JSONArray("[{'id':['5','6','7','8']},{'Tech':['Java']}]"); System.out.println(jsonArray.length()); for(int i=0;i<jsonArray.length();i++){ System.out.println(jsonArray.getJSONObject(i).getString("id")); }Porque en id no tienes una cadena, tienes una matriz de cadenas,
así que en lugar de hacer esto jsonObj.getString("id");
hacer esto
jsonObj.getArray("id"); esto le dará esa matriz a cambio
como si tienes un Json Array en id , entonces tienes que hacer esto
jsonObj.getJSONArray("id");