JsonMappingException when using set instead of list
I have a spring boot project with some objects, in particular I have a Student Class with a DesiredCourses list that should be Set <>.
When I use:
@OneToMany(mappedBy = "student", cascade = CascadeType.ALL)
public List<StudentDesiredCourseEntity> getStudentDesiredCourses() {
return studentDesiredCourses;
}
public void setStudentDesiredCourses(List<StudentDesiredCourseEntity> studentDesiredCourses) {
this.studentDesiredCourses = studentDesiredCourses;
}
Everything works fine, but when I use
@OneToMany(mappedBy = "student", cascade = CascadeType.ALL)
public Set<StudentDesiredCourseEntity> getStudentDesiredCourses() {
return studentDesiredCourses;
}
public void setStudentDesiredCourses(Set<StudentDesiredCourseEntity> studentDesiredCourses) {
this.studentDesiredCourses = studentDesiredCourses;
}
I get
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])
Is there something I am missing or something else that needs to be done?
As requested, equals and 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;
}
+3
source to share
2 answers
Jackson cannot convert json array to hashSet. To do this, you need to create a custom Jackson converter. Here is an example http://kdubblabs.com/java/retrofit-by-square/retrofit-using-jackson-json-conversion/
+2
source to share