使用Set而不是List时的JsonMappingException

时间:2015-04-18 19:18:16

标签: java javascript json spring hibernate

我有一个带有一些实体的spring boot项目,具体来说,我有一个带有DesiredCourses列表的Student Class,它应该是Set<>。

当我使用时:

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

public void setStudentDesiredCourses(List<StudentDesiredCourseEntity> studentDesiredCourses) {
    this.studentDesiredCourses = studentDesiredCourses;
}

一切正常,但是当我使用

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

public void setStudentDesiredCourses(Set<StudentDesiredCourseEntity> studentDesiredCourses) {
    this.studentDesiredCourses = studentDesiredCourses;
}

我得到了

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])

是否有我缺少的东西或需要做些额外的事情?

根据要求,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;
}

2 个答案:

答案 0 :(得分:4)

正如alexwen在评论中所提到的,这不起作用的原因是由于没有处理hashcode / equals方法中的空值

答案 1 :(得分:2)

杰克逊无法将json数组转换为hashSet。为此,您需要创建自定义Jackson Converter。以下是http://kdubblabs.com/java/retrofit-by-square/retrofit-using-jackson-json-conversion/

的示例