HttpMessageNotWritableException: Could not write JSON: EL1025E: The collection has '0' elements, index '0' is invalid

Viewed 226

Json request being sent to backend throws the exception. Where is my mistake?

Could not write JSON: EL1025E: The collection has '0' elements, index '0' is invalid; nested exception is com.fasterxml.jackson.databind.JsonMappingException: EL1025E: The collection has '0' elements, index '0' is invalid (through reference chain: org.springframework.data.domain.PageImpl["content"]->java.util.Collections$UnmodifiableRandomAccessList[3]->com.sun.proxy.$Proxy277["teacherName"])

The server encountered an unexpected condition that prevented it from fulfilling the request.

Java code

public Page<CourseProjection> fetchAllPublishCourses(Integer page, Integer size, String search,
                                                       String sortBy) {
    Page<CourseProjection> response = null;
    JsonParser jsonParser = new JsonParser();
    Specification<Course> spec = null;
    LinkedList<Filter> subjectFilters = new LinkedList<>();
    LinkedList<Filter> subCategoryFilters = new LinkedList<>();
    LinkedList<Filter> examSegmentFilters = new LinkedList<>();
    LinkedList<Filter> categoryFilters = new LinkedList<>();
    LinkedList<Filter> otherFilters = new LinkedList<>();

    try {
      Pageable pageable = null;
      Sort sort = null;
      if (search != null && !search.isEmpty()) {
        JsonObject jsonObject = (JsonObject) jsonParser.parse(search);
        if (jsonObject != null) {

          JsonArray jsonArray = (JsonArray) jsonObject.get("filters");

          for (int i = 0; i < jsonArray.size(); i++) {
            Filter filter = new Filter();
            filter.setFilterName(
              ((JsonObject) jsonArray.get(i)).get("filterName").toString().replaceAll("\"", ""));
            filter.setValue(
              ((JsonObject) jsonArray.get(i)).get("value").toString().replaceAll("\"", ""));

            if (filter.getFilterName().equalsIgnoreCase("courseSubject")) {
              subjectFilters.add(filter);
            } else if (filter.getFilterName().equalsIgnoreCase("courseSubCategory")) {
              subCategoryFilters.add(filter);
            } else if (filter.getFilterName().equalsIgnoreCase("courseExamSegment")) {
              examSegmentFilters.add(filter);
            } else if (filter.getFilterName().equalsIgnoreCase("courseCategory")) {

              if (filter.getValue().equalsIgnoreCase("current affairs")) {
                Filter currentAffairsFilter = new Filter();
                currentAffairsFilter.setFilterName("courseSubject");
                currentAffairsFilter.setValue("Current Affairs");
                subjectFilters.add(currentAffairsFilter);
              } else {
                categoryFilters.add(filter);
              }

            } else {
              otherFilters.add(filter);
            }
          }
          otherFilters.add(Filter.addDeafultFilter());

        }
        if (otherFilters != null && otherFilters.size() > 0) {

          CourseSpecificationBuilder builder = new CourseSpecificationBuilder();
          spec = builder.build(otherFilters, subjectFilters, subCategoryFilters, examSegmentFilters,
            categoryFilters);

        }

      }
      if (sortBy != null && !sortBy.isEmpty()) {

        switch (sortBy) {
          case "atoz":
            sort = new Sort(Direction.ASC, new String[]{"courseTitle"});
            break;
          case "ztoa":
            sort = new Sort(Direction.DESC, new String[]{"courseTitle"});
            break;
          case "popular":
            sort = new Sort(Direction.ASC, "position");
            break;
        }
      }

      if (spec != null) {
        if (page != null && size != null) {

          if (sort != null) {
            pageable = PageRequest.of(page, size, sort);
            response = courseRepository.findAll(spec, CourseProjection.class, pageable);
          } else {
            pageable = PageRequest.of(page, size);
            response = courseRepository.findAll(spec, CourseProjection.class, pageable);
          }

        } else {
          pageable = PageRequest.of((page != null ? page : 0), (size != null ? size : 0));
          response = courseRepository.findAll(spec, CourseProjection.class, pageable);
        }
      }

    } catch (Exception e) {
      LOGGER.error(Course.class.getName() + " Exception Occurred");
      emailService.sendErrorLogsToDevelopers(ExceptionUtils.getStackTrace(e));
    }

    return response;
  }

JavaScript

  var obj2 = JSON.stringify(obj);
  $.ajax({
    url: apiBasePath + '/courses?page=' + page_num + '&size=12&sort='
      + sortCourses + '&search='
      + encodeURIComponent(JSON.stringify(obj)),
    type: "GET",
    dataType: "json",
    contentType: "application/json; charset=utf-8",
    success: function (response) {
      console.log("Success : " + response);
      $('.load-courses-progress-bar').hide();
      $('.course-listing').css("visibility", "visible");
      $('.mat-content').css("overflow-y", "auto")

      if ($(window).width() > '767') {
        $('body,html').animate({
          scrollTop: $(".course-listing").offset().top - 100
        }, 1000);
        setTimeout(function () {
          $('.mat-all-curses-main-tab').hide();
        }, 2000);
      } else {
        $(".mat-all-curses-main-tab-mobile").hide("0", function () {
          $('body,html').animate({
            scrollTop: $(".course-listing").offset().top - 200
          }, 1000);
        })
      }
      showCourses(response);
      showTrendingCourse(response, obj);
    },

    error: function (response) {
      console.log("Error : " + JSON.stringify(response));
    }
  });
0 Answers
Related