简体   繁体   中英

how to parse complicated json in android

I have been following a tutorial and finally have understand to a decent degree using AsyncTask and how to send an http get request to get the json returned. I can get the json, I think successfully but am having trouble parsing it.

The tutorial I was looking at uses a pretty simple weather api which sends back pretty easy json to parse.

Mine is a search result with info on each item. My json looks like this:

http://pastebin.com/f65hNx0z

I realize the difference between json objects and the arrays of info. Just a bit confused on how to parse over to get information on each beer and the brewery info.

My code below:

String jsonUrl = url + query;
            Toast.makeText(this, jsonUrl, Toast.LENGTH_SHORT).show();

            //todo: get json 
            new ReadJSONResult().execute(jsonUrl);

            return false;
        }

        private class ReadJSONResult extends AsyncTask
        <String, Void, String> {
            protected String doInBackground(String... urls) {
                return readJSONFeed(urls[0]);
            }

            protected void onPostExecute(String result) {
                try {

                    ///code below is what I kow I need to reconstruct and change to parse
                    JSONObject jsonObject = new JSONObject(result);
                    JSONObject weatherObservationItems = 
                        new JSONObject(jsonObject.getString("weatherObservation"));

                    Toast.makeText(getBaseContext(), 
                        weatherObservationItems.getString("clouds") + 
                     " - " + weatherObservationItems.getString("stationName"), 
                     Toast.LENGTH_SHORT).show();


                } catch (Exception e) {
                    Log.d("ReadWeatherJSONFeedTask", e.getLocalizedMessage());
                }          
            }
        }

You should use a JSON deserializer library to object which supports nested objects, also. I recommend Gson https://code.google.com/p/google-gson/

There is a Java class generator from JSON response. jsongen.byingtondesign.com will parse your json response and give you Java Bean class. which will help you to understand the need.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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