大家好,我试图解析json,但文本永远不会显示!在logcat中它说:
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)
我不知道为什么,这是我的代码:
@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);
}
}
这将是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
}
如果有人能告诉我哪些错误会受到赞赏
先谢谢
答案 0 :(得分:2)
尝试以下代码: -
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
}
你的产品公司数据是来自json数组,你将产品公司的数据视为json对象。
答案 1 :(得分:1)
production_companies
是JSONArray
而不是JSONObject
,因此解析器正确地告诉您密钥JSONObject
{}没有production_companies
p>
答案 2 :(得分:-1)
收到输入流后,将其转换为字符串。转换字符串后,任何jason标签都存在于字符串中。如果存在则解析json数据。