简体   繁体   中英

Parsing data from json

JSON data

{
    "kind": "books#volumes",
    "totalItems": 111,
    "items": [{
        "kind": "books#volume",
        "id": "wmMmkAFHlfAC",
        "etag": "m5G7DGubjpc",
        "selfLink": "https://www.googleapis.com/books/v1/volumes/wmMmkAFHlfAC",
        "volumeInfo": {
            "title": "They!",
            "authors": ["Chuck Keyes"],
            "publisher": "Larry Larson",
            "publishedDate": "2011-09-08",
            "industryIdentifiers": [{
                "type": "ISBN_13",
                "identifier": "9781465704771"
            },
            {
                "type": "ISBN_10",
                "identifier": "1465704779"
            }],
            "readingModes": {
                "text": true,
                "image": true
            },
            "printType": "BOOK",
            "categories": ["Fiction"],
            "maturityRating": "NOT_MATURE",
            "allowAnonLogging": false,
            "contentVersion": "0.2.1.0.preview.3",
            "panelizationSummary": {
                "containsEpubBubbles": false,
                "containsImageBubbles": false
            },
            "imageLinks": {
                "smallThumbnail": "http://books.google.com/books/content?id=wmMmkAFHlfAC&printsec=frontcover&img=1&zoom=5&edge=curl&source=gbs_api",
                "thumbnail": "http://books.google.com/books/content?id=wmMmkAFHlfAC&printsec=frontcover&img=1&zoom=1&edge=curl&source=gbs_api"
            },
            "language": "en",
            "previewLink": "http://books.google.co.in/books?id=wmMmkAFHlfAC&pg=PT220&dq=roses+inauthor:keyes&hl=&cd=1&source=gbs_api",
            "infoLink": "http://books.google.co.in/books?id=wmMmkAFHlfAC&dq=roses+inauthor:keyes&hl=&source=gbs_api",
            "canonicalVolumeLink": "https://books.google.com/books/about/They.html?hl=&id=wmMmkAFHlfAC"
        },
        "saleInfo": {
            "country": "IN",
            "saleability": "NOT_FOR_SALE",
            "isEbook": false
        },
        "accessInfo": {
            "country": "IN",
            "viewability": "PARTIAL",
            "embeddable": true,
            "publicDomain": false,
            "textToSpeechPermission": "ALLOWED",
            "epub": {
                "isAvailable": true,
                "acsTokenLink": "http://books.google.co.in/books/download/They-sample-epub.acsm?id=wmMmkAFHlfAC&format=epub&output=acs4_fulfillment_token&dl_type=sample&source=gbs_api"
            },
            "pdf": {
                "isAvailable": true,
                "acsTokenLink": "http://books.google.co.in/books/download/They-sample-pdf.acsm?id=wmMmkAFHlfAC&format=pdf&output=acs4_fulfillment_token&dl_type=sample&source=gbs_api"
            },
            "webReaderLink": "http://play.google.com/books/reader?id=wmMmkAFHlfAC&hl=&printsec=frontcover&output=reader&source=gbs_api",
            "accessViewStatus": "SAMPLE",
            "quoteSharingAllowed": false
        },
        "searchInfo": {
            "textSnippet": "She quickly returned with the bouquet of mixed colored \u003cb\u003eroses\u003c/b\u003e surrounded with \u003cbr\u003e\nbaby's breath. "These are mine! My husband has never given me such a beautiful \u003cbr\u003e\nbouquet of \u003cb\u003eroses\u003c/b\u003e." "Armed home invaders possessed by a deranged queen ..."
        }
    }]
}

My code to fetch data

private static List<Word> extractFeatureFromJson(String earthquakeJSON) {
        // If the JSON string is empty or null, then return early.
        if (TextUtils.isEmpty(earthquakeJSON)) {
            return null;
        }

        // Create an empty ArrayList that we can start adding earthquakes to

        List<Word> earthquakes = new ArrayList<>();


        // Try to parse the JSON response string. If there's a problem with the way the JSON
        // is formatted, a JSONException exception object will be thrown.
        // Catch the exception so the app doesn't crash, and print the error message to the logs.
        try {


            // Create a JSONObject from the JSON response string
            JSONObject baseJsonResponse = new JSONObject(earthquakeJSON);
            // Extract the JSONArray associated with the key called "features",
            // which represents a list of features (or earthquakes).
            JSONArray earthquakeArray = baseJsonResponse.getJSONArray("items");
            // For each earthquake in the earthquakeArray, create an {@link EarthquakeAdapter} object
            for (int i = 0; i < earthquakeArray.length(); i++) {

                // Get a single earthquake at position i within the list of earthquakes
                JSONObject currentEarthquake = earthquakeArray.getJSONObject(i);

                // For a given earthquake, extract the JSONObject associated with the
                // key called "properties", which represents a list of all properties
                // for that earthquake.
                JSONObject properties = currentEarthquake.getJSONObject("volumeInfo");

                // Extract the value for the key called "mag"

                String location = currentEarthquake.getString("title");

                double magnitude = currentEarthquake.getDouble("publishedDate");
                // Extract the value for the key called "time"
                long time = currentEarthquake.getLong("pageCount");

                // Extract the value for the key called "url"
                String url = currentEarthquake.getString("description");

                // Create a new {@link EarthquakeAdapter} object with the magnitude, location, time,
                // and url from the JSON response.
                Word earthquake = new Word(magnitude, location, time, url);

                // Add the new {@link EarthquakeAdapter} to the list of earthquakes.
                earthquakes.add(earthquake);
            }

        } catch (JSONException e) {
            // If an error is thrown when executing any of the above statements in the "try" block,
            // catch the exception here, so the app doesn't crash. Print a log message
            // with the message from the exception.
            Log.e("QueryUtils", "Problem parsing the earthquake JSON results", e);
        }
        // Return the list of earthquakes
        return earthquakes;
    }

I have taken this Json data and tried to fetch from the above code but it is not working. Error that is shown is

"Problem parsing the earthquake JSON results org.json.JSONException: No value for title"

"Problem parsing the earthquake JSON results org.json.JSONException : No value for title ".

Use properties.getString("title") instead of currentEarthquake.getString("title") and to get description , pageCount , publishedDate and thumbnail try my below codes.

Try this:

try {

        JSONObject baseJsonResponse = new JSONObject(earthquakeJSON);
        JSONArray earthquakeArray = baseJsonResponse.getJSONArray("items");
        for (int i = 0; i < earthquakeArray.length(); i++) {

            JSONObject currentEarthquake = earthquakeArray.getJSONObject(i);

            JSONObject volumeInfo = currentEarthquake.getJSONObject("volumeInfo");
            String title = volumeInfo.getString("title");

            String publishedDate = volumeInfo.getString("publishedDate");
            String description = volumeInfo.getString("description");
            int pageCount = volumeInfo.getInt("pageCount");

            JSONObject imageLinks = volumeInfo.getJSONObject("imageLinks");
            String thumbnail = imageLinks.getString("thumbnail");

            ....................
            ..........................
        }

    } catch (JSONException e) {
        // If an error is thrown when executing any of the above statements in the "try" block,
        // catch the exception here, so the app doesn't crash. Print a log message
        // with the message from the exception.
        Log.e("QueryUtils", "Problem parsing the earthquake JSON results", e);
    }

FYI, There is no averageRating key in your json.

As far as I can see, the error lies in the root object, where you try to fetch the title from.

            // For a given earthquake, extract the JSONObject associated with the
            // key called "properties", which represents a list of all properties
            // for that earthquake.
            JSONObject properties = currentEarthquake.getJSONObject("volumeInfo");

            // Extract the value for the key called "mag"

            String location = currentEarthquake.getString("title");

title is not a child of currentEarthquake but of volumeInfo .

            String location = properties.getString("title");

should be correct.

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