Java 使用集合而不是列表时出现JsonMappingException

Java 使用集合而不是列表时出现JsonMappingException,java,javascript,json,spring,hibernate,Java,Javascript,Json,Spring,Hibernate,我有一个SpringBoot项目和一些实体,具体地说,我有一个学生班,有一个DesiredCourses列表,应该是一个集合 当我使用: @OneToMany(mappedBy = "student", cascade = CascadeType.ALL) public List<StudentDesiredCourseEntity> getStudentDesiredCourses() { return studentDesiredCourses; } public vo

我有一个SpringBoot项目和一些实体,具体地说,我有一个学生班,有一个DesiredCourses列表,应该是一个集合

当我使用:

@OneToMany(mappedBy = "student", cascade = CascadeType.ALL)
public List<StudentDesiredCourseEntity> getStudentDesiredCourses() {
    return studentDesiredCourses;
}

public void setStudentDesiredCourses(List<StudentDesiredCourseEntity> studentDesiredCourses) {
    this.studentDesiredCourses = studentDesiredCourses;
}
我是否有什么遗漏或需要做的额外工作

根据请求,equals和hashcode

@Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (!(o instanceof StudentDesiredCourseEntity)) return false;

    StudentDesiredCourseEntity that = (StudentDesiredCourseEntity) o;

    if (!course.equals(that.course)) return false;
    if (!priority.equals(that.priority)) return false;
    if (!student.equals(that.student)) return false;

    return true;
}

@Override
public int hashCode() {
    int result = priority.hashCode();
    result = 31 * result + course.hashCode();
    result = 31 * result + student.hashCode();
    return result;
}

Jackson无法将json数组转换为哈希集。为此,您需要创建一个自定义的Jackson转换器。下面是alexwen在评论中提到的一个例子,这个例子不起作用的原因是hashcode/equals方法中没有处理空值。我认为这是一个非常常见的请求,它将被自动处理……Jackson支持集合,我想这里可能发生了其他事情。我想知道HashCode或Equals方法是否是罪魁祸首。你有学生DesiredCourseentity的HashCode和Equals吗?发布了Equals和hash Codeahh你知道吗,我从来没有考虑过我的学生或课程会返回为空。。。。我敢打赌这就是问题所在。非常感谢@alexwen,就是这样!
org.springframework.http.converter.HttpMessageNotReadableException",
"message":"Could not read JSON: (was java.lang.NullPointerException) (through reference chain: edu.cs6310.project4.entities.StudentEntity[\"studentDesiredCourses\"]->java.util.HashSet[0]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: (was java.lang.NullPointerException) (through reference chain: edu.cs6310.project4.entities.StudentEntity[\"studentDesiredCourses\"]->java.util.HashSet[0])
@Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (!(o instanceof StudentDesiredCourseEntity)) return false;

    StudentDesiredCourseEntity that = (StudentDesiredCourseEntity) o;

    if (!course.equals(that.course)) return false;
    if (!priority.equals(that.priority)) return false;
    if (!student.equals(that.student)) return false;

    return true;
}

@Override
public int hashCode() {
    int result = priority.hashCode();
    result = 31 * result + course.hashCode();
    result = 31 * result + student.hashCode();
    return result;
}