java - 解析json数据

标签 java android json parsing

JSON 数据

{
    "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 ..."
        }
    }]
}

我的获取数据的代码

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;
    }

我已经获取了这个 Json 数据并尝试从上面的代码中获取,但它不起作用。 显示的错误是

“解析地震 JSON 结果 org.json.JSONException 时出现问题:标题没有值”

最佳答案

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

使用 properties.getString("title") 而不是 currentEarthquake.getString("title") 并获取 descriptionpageCountpublishedDatethumbnail 尝试我的以下代码。

试试这个:

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);
    }

仅供引用,您的 json 中没有 averageRating 键。

关于java - 解析json数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43857124/

相关文章:

java - Spring 的弃用警告

java - 验证用户从文本框输入的内容#

Java 如何提高读取 50G 文件的能力

python - 适用于 python2.7 的 Google 表格 API --> "Invalid JSON payload. Root element must be a message"

javascript - 我不明白clearInterval()

java - 如果您在 Java 中显式初始化一个 Object 数组,包含 "new Object[]"与不包含它是否不同?

java - 当 wait() 不可用时节省 CPU

java - 搜索前 3 个数字的最快和最有效的方法?

android - 无法在 Android 设备的/data/user/0 的子目录中捕获文件

json - Json 的 Jmeter CSV 文件