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

huangapple 未分类评论47阅读模式
英文:

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

问题

Json请求发送到后端时抛出异常。我的错误在哪里?

无法编写JSON:EL1025E:集合有'0'个元素,索引'0'无效;嵌套异常是com.fasterxml.jackson.databind.JsonMappingException:EL1025E:集合有'0'个元素,索引'0'无效(通过引用链:org.springframework.data.domain.PageImpl["content"]->java.util.Collections$UnmodifiableRandomAccessList[3]->com.sun.proxy.$Proxy277["teacherName"])

服务器遇到了意外情况,阻止了它无法完成请求。

Java代码

public Page<CourseProjection> fetchAllPublishCourses(Integer page, Integer size, String search,
                                                     String sortBy) {
    // ...(代码中的其他部分)
}

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) {
        // ...(代码中的其他部分)
    },

    error: function (response) {
        // ...(代码中的其他部分)
    }
});
英文:

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&lt;CourseProjection&gt; fetchAllPublishCourses(Integer page, Integer size, String search,
                                                       String sortBy) {
    Page&lt;CourseProjection&gt; response = null;
    JsonParser jsonParser = new JsonParser();
    Specification&lt;Course&gt; spec = null;
    LinkedList&lt;Filter&gt; subjectFilters = new LinkedList&lt;&gt;();
    LinkedList&lt;Filter&gt; subCategoryFilters = new LinkedList&lt;&gt;();
    LinkedList&lt;Filter&gt; examSegmentFilters = new LinkedList&lt;&gt;();
    LinkedList&lt;Filter&gt; categoryFilters = new LinkedList&lt;&gt;();
    LinkedList&lt;Filter&gt; otherFilters = new LinkedList&lt;&gt;();

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

          JsonArray jsonArray = (JsonArray) jsonObject.get(&quot;filters&quot;);

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

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

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

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

        }
        if (otherFilters != null &amp;&amp; otherFilters.size() &gt; 0) {

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

        }

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

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

      if (spec != null) {
        if (page != null &amp;&amp; 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() + &quot; Exception Occurred&quot;);
      emailService.sendErrorLogsToDevelopers(ExceptionUtils.getStackTrace(e));
    }

    return response;
  }

JavaScript

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

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

    error: function (response) {
      console.log(&quot;Error : &quot; + JSON.stringify(response));
    }
  });

huangapple
  • 本文由 发表于 2020年7月27日 13:27:34
  • 转载请务必保留本文链接:https://java.coder-hub.com/63109158.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定