'org.json.JSONException: No value for trying to parse a JSON
Hello everyone I am trying to parse a json but the text is never displayed! In the logcat it says this:
06-24 23:28:22.681: W/System.err(6271): org.json.JSONException: No value for production_companies
06-24 23:28:22.681: W/System.err(6271): at org.json.JSONObject.get(JSONObject.java:355)
06-24 23:28:22.682: W/System.err(6271): at org.json.JSONObject.getJSONObject(JSONObject.java:574)
06-24 23:28:22.682: W/System.err(6271): at com.example.movieinfo.MainActivity$MyAsyncTask.doInBackground(MainActivity.java:126)
06-24 23:28:22.682: W/System.err(6271): at com.example.movieinfo.MainActivity$MyAsyncTask.doInBackground(MainActivity.java:1)
06-24 23:28:22.683: W/System.err(6271): at android.os.AsyncTask$2.call(AsyncTask.java:288)
06-24 23:28:22.683: W/System.err(6271): at java.util.concurrent.FutureTask.run(FutureTask.java:237)
06-24 23:28:22.683: W/System.err(6271): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
06-24 23:28:22.684: W/System.err(6271): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
06-24 23:28:22.684: W/System.err(6271): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
06-24 23:28:22.685: W/System.err(6271): at java.lang.Thread.run(Thread.java:841)
I don't know why, this is my code:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getSupportActionBar().setCustomView(R.layout.actionbar);
android.app.ActionBar bar = getActionBar();
bar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#3498db")));
ImageView search = (ImageView) findViewById(R.id.search);
box = (EditText) findViewById(R.id.editText1);
search.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
url = "https://api.themoviedb.org/3/movie/" + box.getText().toString() + "?api_key=xxx";
new MyAsyncTask().execute();
}
});
}
private class MyAsyncTask extends AsyncTask<String, String, String>{
@Override
protected String doInBackground(String... arg0) {
//Creamos el cliente HTTP
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
//Pasamos por POST la url
HttpPost htppost = new HttpPost(url);
//Definimos que tipo de dato nos pasan
htppost.setHeader("Content-type", "application/json");
//Leer data del URL
InputStream inputStream = null;
String result = null;
try{
//Pedir una respuesta de la pagina
HttpResponse response = httpclient.execute(htppost);
//Guarda todo el contenido
HttpEntity entity = response.getEntity();
//Obtenog el contenido
inputStream = entity.getContent();
//Lee todo el contenido
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
//Guarda todo ahi
StringBuilder theStringBuilder = new StringBuilder();
String line = null;
//Aca leemos todo
while((line = reader.readLine()) != null){
theStringBuilder .append(line + "\n");
}
//Pasamos todo a result
result = theStringBuilder.toString();
}catch(Exception e){
e.printStackTrace();
}finally{
try{
//Si se guardo algo cerramos el input stream
if(inputStream != null){
inputStream.close();
}else{
Log.e("No funciono", "Cerrar el inputStream");
}
}catch(Exception e){
e.printStackTrace();
}
}
JSONObject jsonObject;
try{
// Hacemos que el resultado sea un JSONObject
jsonObject = new JSONObject(result);
// Buscamos el objeto query "Objeto"
JSONObject queryJSONOBject = jsonObject.getJSONObject("production_companies");
// Finalmente obtenemos los strings
titulo = jsonObject.getString("original_title");
descripcion = queryJSONOBject.getString("name");
imageUrl = jsonObject.getString("poster_path");
}catch(JSONException e){
e.printStackTrace();
}
return result;
}
@Override
protected void onPostExecute(String result) {
Toast.makeText(getApplicationContext(), titulo, Toast.LENGTH_SHORT).show();
TextView line1 = (TextView) findViewById(R.id.titulo);
TextView line2 = (TextView) findViewById(R.id.descr);
line1.setText(titulo);
line2.setText(descripcion);
}
}
This would be the json
{
"adult": false,
"backdrop_path": "/h5ILYBMAYAlZbMypIImmSr2NGqZ.jpg",
"belongs_to_collection": null,
"budget": 6000000,
"genres": [
{
"id": 35,
"name": "Comedy"
},
{
"id": 18,
"name": "Drama"
},
{
"id": 14,
"name": "Fantasy"
}
],
"homepage": "http://www.lasciencedesreves-lefilm.com/accueil.htm",
"id": 300,
"imdb_id": "tt0354899",
"original_title": "La science des rêves",
"overview": "A man entranced by his dreams and imagination is lovestruck with a French woman and feels he can show her his world.",
"popularity": 0.991891956045027,
"poster_path": "/8juTRqn5o43mnlVacp1IzZSd11N.jpg",
"production_companies": [
{
"name": "Partizan Films",
"id": 11911
},
{
"name": "Gaumont",
"id": 9
},
{
"name": "France 3 Cinéma",
"id": 591
},
{
"name": "Canal+",
"id": 5358
},
{
"name": "TPS Star",
"id": 6586
},
{
"name": "Mikado Film",
"id": 11912
}
],
"production_countries": [
{
"iso_3166_1": "FR",
"name": "France"
},
{
"iso_3166_1": "IT",
"name": "Italy"
}
],
"release_date": "2006-02-11",
"revenue": 9524340,
"runtime": 105,
"spoken_languages": [
{
"iso_639_1": "en",
"name": "English"
},
{
"iso_639_1": "es",
"name": "Español"
},
{
"iso_639_1": "fr",
"name": "Français"
}
],
"status": "Released",
"tagline": "Close your eyes. Open your heart.",
"title": "The Science of Sleep",
"vote_average": 7.7,
"vote_count": 27
}
If anybody could tell me what's wrong it would be appreciated.
Solution 1:[1]
try below code :-
try
{
JSONObject jsonObject = new JSONObject(result);
// Buscamos el objeto query "Objeto"
JSONArray queryJSONOBject = jsonObject.getJSONArray("production_companies");
// Finalmente obtenemos los strings
String descripcion = "" ;//= new String[queryJSONOBject.length()];
for (int i = 0; i < queryJSONOBject.length(); i++)
{
JSONObject j = queryJSONOBject.getJSONObject(i);
descripcion = descripcion + j.getString("name")+ " / ";
}
String titulo = jsonObject.getString("original_title");
String imageUrl = jsonObject.getString("poster_path");
System.out.println(titulo);
System.out.println(imageUrl);
System.out.println(descripcion);
}
catch (Exception e)
{
// TODO: handle exception
}
Thing is your product companies data comes from json array and you treated product companies data as a json object.
Solution 2:[2]
production_companies
is a JSONArray
not a JSONObject
, and so the parser is correctly telling you that there is no JSONObject
for the key production_companies
Solution 3:[3]
Once you received inputstream then convert it into string. After to convert string check any jason tag is exist into string. If exists then parse json data.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | duggu |
Solution 2 | panini |
Solution 3 | R K Infotech |