简体   繁体   English

如何从JSON结果中检索流派

[英]How to retrieve genre from JSON result

I can not retrieve all key values from JSON object retrieved from HTTP request. 我无法从HTTP请求中检索的JSON对象中检索所有键值。

This is the returned JSON object from http request: 这是来自http请求的返回JSON对象:

 {"data":[{"movie_id":3,"movie_name":"Promithius","genre":"a dude","year":"2016","rating":45}]}

my Android Code: 我的Android代码:

 try {
                //HttpJsonParser httpJsonParser = new HttpJsonParser();
                JSONObject JSonObj = (JSONObject)  new 
 JSONTokener(result).nextValue();
                String mymovie = JSonObj.getString("movie_name" );
                String movieGenre = JSonObj.getString("genre" );
                etResponse.setText("movie=" + mymovie + " genre=" + 
 movieGenre);

            } catch (JSONException e) {
                etResponse.setText("ERROR=" + e.getMessage());
                e.printStackTrace();
            }

When I run it in emulator with only: 当我在模拟器中运行它时只有:

 String mymovie = JSonObj.getString("movie_name" );
 etResponse.setText("movie=" + mymovie;

I get back the Movie name with no error. 我没有错误地取回电影名称。 So the issue is I can retrieve movie_name but no Genre. 所以问题是我可以检索movie_name但没有类型。 Error returned says "No value for genre" Thanks in advance. 返回错误说“没有类型的价值”提前谢谢。

I think the data is JSONArray. 我认为数据是JSONArray。

String result = "{\"data\":[{\"movie_id\":3,\"movie_name\":\"Promithius\",\"genre\":\"a dude\",\"year\":\"2016\",\"rating\":45}]}";

        try {
            JSONObject JSonObj = (JSONObject)  new JSONTokener(result).nextValue();
            JSONArray data = JSonObj.getJSONArray("data");

            for (int i=0; i<data.length(); i++){
                JSONObject jsonObject = data.getJSONObject(i);
                String mymovie = jsonObject.getString("movie_name" );
                String movieGenre = jsonObject.getString("genre" );
                String dest = "movie=" + mymovie + " genre=" + movieGenre;
                Log.d(TAG, dest);
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }

Below is the code that finally worked for me. 下面是最终为我工作的代码。 I hope it can help someone else. 我希望它可以帮助别人。

 try{
 JSONObject object = new JSONObject(result);
 JSONArray Jarray  = object.getJSONArray("data");
 object = Jarray.getJSONObject(0);
 String MovieName = object.getString("movie_name");
 String Genre = object.getString("genre");
 String Rating = object.getString("rating");
 String Year = object.getString("year");
 etResponse.setText("Movie Name = " + MovieName + " \n Genre = " + 
 Genre + "\n Rating = " + Rating + " \n Year = " + Year );
    } catch (JSONException e) {
    etResponse.setText("JSONException: " + e.getMessage());
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM