Пропустить первый цикл цикла, когда «Категории равны нулю» - PullRequest
1 голос
/ 08 апреля 2019

Я читаю данные из файла json, и я хочу получить элементы по категориям

 public List<Item> getItemsByCategory(String category) {
        List<Item> matchingCategory = new ArrayList<>();
        for (Item item : books.getItems()) {
            List<String> categories1 = item.getVolumeInfo().getCategories();
            // categories1 == null for the first item  so the below for loop fails
            for (String cat : categories1) {
                if (cat.equals(category)) {
                    matchingCategory.add(item);
                } else throw new MyResourceNotFoundException(String.format("category with type %s is not found"));
            }
        }
        return matchingCategory;
    }

Мой первый элемент в файле json не имеет категории, поэтому категории в первом цикле являются нулевымиКак я могу пропустить его и продолжить в элементе в файле JSON, Вместо того чтобы получить исключение нулевого указателя

Я пытался использовать разрыв, но он завершает цикл без запуска следующего

Это мойjson, я читаю данные отсюда.

{
  "requestedUrl": "https://www.googleapis.com/books/v1/volumes?q=java&maxResults=40",
  "items": [
    {
      "kind": "books#volume",
      "id": "7tkN1CYzn2cC",
      "etag": "pfjjxSpetIM",
      "selfLink": "https://www.googleapis.com/books/v1/volumes/7tkN1CYzn2cC",
      "volumeInfo": {
        "title": "A Hypervista of the Java Landscape",
        "publisher": "InfoStrategist.com",
        "industryIdentifiers": [
          {
            "type": "ISBN_13",
            "identifier": "9781592432172"
          },
          {
            "type": "ISBN_10",
            "identifier": "1592432174"
          }
        ],
        "readingModes": {
          "text": true,
          "image": true
        },
        "printType": "BOOK",
        "maturityRating": "NOT_MATURE",
        "allowAnonLogging": false,
        "contentVersion": "1.0.1.0.preview.3",
        "imageLinks": {
          "smallThumbnail": "http://books.google.com/books/content?id=7tkN1CYzn2cC&printsec=frontcover&img=1&zoom=5&edge=curl&source=gbs_api",
          "thumbnail": "http://books.google.com/books/content?id=7tkN1CYzn2cC&printsec=frontcover&img=1&zoom=1&edge=curl&source=gbs_api"
        },
        "language": "en",
        "previewLink": "http://books.google.pl/books?id=7tkN1CYzn2cC&pg=PP1&dq=java&hl=&cd=1&source=gbs_api",
        "infoLink": "http://books.google.pl/books?id=7tkN1CYzn2cC&dq=java&hl=&source=gbs_api",
        "canonicalVolumeLink": "https://books.google.com/books/about/A_Hypervista_of_the_Java_Landscape.html?hl=&id=7tkN1CYzn2cC"
      },
      "saleInfo": {
        "country": "PL",
        "saleability": "NOT_FOR_SALE",
        "isEbook": false
      },
      "accessInfo": {
        "country": "PL",
        "viewability": "PARTIAL",
        "embeddable": true,
        "publicDomain": false,
        "textToSpeechPermission": "ALLOWED",
        "epub": {
          "isAvailable": true,
          "acsTokenLink": "http://books.google.pl/books/download/A_Hypervista_of_the_Java_Landscape-sample-epub.acsm?id=7tkN1CYzn2cC&format=epub&output=acs4_fulfillment_token&dl_type=sample&source=gbs_api"
        },
        "pdf": {
          "isAvailable": true,
          "acsTokenLink": "http://books.google.pl/books/download/A_Hypervista_of_the_Java_Landscape-sample-pdf.acsm?id=7tkN1CYzn2cC&format=pdf&output=acs4_fulfillment_token&dl_type=sample&source=gbs_api"
        },
        "webReaderLink": "http://play.google.com/books/reader?id=7tkN1CYzn2cC&hl=&printsec=frontcover&source=gbs_api",
        "accessViewStatus": "SAMPLE",
        "quoteSharingAllowed": false
      }
    },
    {
      "kind": "books#volume",
      "id": "-SYM4PW-YAgC",
      "etag": "dXytGSDckJk",
      "selfLink": "https://www.googleapis.com/books/v1/volumes/-SYM4PW-YAgC",
      "volumeInfo": {
        "title": "The Religion of Java",
        "authors": [
          "Clifford Geertz"
        ],
        "publisher": "University of Chicago Press",
        "publishedDate": "1976-02-15",
        "description": "Written with a rare combination of analysis and speculation, this comprehensive study of Javanese religion is one of the few books on the religion of a non-Western people which emphasizes variation and conflict in belief as well as similarity and harmony. The reader becomes aware of the intricacy and depth of Javanese spiritual life and the problems of political and social integration reflected in the religion. The Religion of Java will interest specialists in Southeast Asia, anthropologists and sociologists concerned with the social analysis of religious belief and ideology, students of comparative religion, and civil servants dealing with governmental policy toward Indonesia and Southeast Asia.",
        "industryIdentifiers": [
          {
            "type": "ISBN_10",
            "identifier": "0226285103"
          },
          {
            "type": "ISBN_13",
            "identifier": "9780226285108"
          }
        ],
        "readingModes": {
          "text": true,
          "image": true
        },
        "pageCount": 392,
        "printType": "BOOK",
        "categories": [
          "Religion"
        ],
        "averageRating": 4.0,
        "ratingsCount": 4,
        "maturityRating": "NOT_MATURE",
        "allowAnonLogging": false,
        "contentVersion": "2.1.2.0.preview.3",
        "imageLinks": {
          "smallThumbnail": "http://books.google.com/books/content?id=-SYM4PW-YAgC&printsec=frontcover&img=1&zoom=5&edge=curl&source=gbs_api",
          "thumbnail": "http://books.google.com/books/content?id=-SYM4PW-YAgC&printsec=frontcover&img=1&zoom=1&edge=curl&source=gbs_api"
        },
        "language": "en",
        "previewLink": "http://books.google.pl/books?id=-SYM4PW-YAgC&printsec=frontcover&dq=java&hl=&cd=2&source=gbs_api",
        "infoLink": "http://books.google.pl/books?id=-SYM4PW-YAgC&dq=java&hl=&source=gbs_api",
        "canonicalVolumeLink": "https://books.google.com/books/about/The_Religion_of_Java.html?hl=&id=-SYM4PW-YAgC"
      },
      "saleInfo": {
        "country": "PL",
        "saleability": "NOT_FOR_SALE",
        "isEbook": false
      },
      "accessInfo": {
        "country": "PL",
        "viewability": "PARTIAL",
        "embeddable": true,
        "publicDomain": false,
        "textToSpeechPermission": "ALLOWED",
        "epub": {
          "isAvailable": true,
          "acsTokenLink": "http://books.google.pl/books/download/The_Religion_of_Java-sample-epub.acsm?id=-SYM4PW-YAgC&format=epub&output=acs4_fulfillment_token&dl_type=sample&source=gbs_api"
        },
        "pdf": {
          "isAvailable": false
        },
        "webReaderLink": "http://play.google.com/books/reader?id=-SYM4PW-YAgC&hl=&printsec=frontcover&source=gbs_api",
        "accessViewStatus": "SAMPLE",
        "quoteSharingAllowed": false
      },
      "searchInfo": {
        "textSnippet": "Written with a rare combination of analysis and speculation, this comprehensive study of Javanese religion is one of the few books on the religion of a non-Western people which emphasizes variation and conflict in belief as well as ..."
      }
    } etc 

Как указано выше, у первого элемента нет категории, но у второго есть, поэтому я должен иметь возможность получить второй, он

Ответы [ 2 ]

1 голос
/ 08 апреля 2019

Вот то, что я сделал, используя «продолжить» и «прервать», но мне пришлось удалить обработчик исключений,

  public List<Item> getItemsByCategory(String category) {
        List<Item> matchingCategory = new ArrayList<>();
        for (Item item : books.getItems()) {
            List<String> categories1 = item.getVolumeInfo().getCategories();
            if(categories1 == null) continue;
            for (String cat : categories1) {
                if (cat.equals(category)) {
                    matchingCategory.add(item);
                } else break;   //throw new MyResourceNotFoundException(String.format("category with type %s is not found", category));
            }
        }
        return matchingCategory;
    }

Как я могу вернуть новое исключение

0 голосов
/ 08 апреля 2019

Почему вы не можете добавить условие ..?

if(categories1 != null) {
    for() {
        ...
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...