调用RESTful服务时发生JsonMappingException

时间:2017-07-11 14:16:54

标签: java json hibernate rest

我正在使用带有Spring,Hibernate和JPA的Java8。

我有一个RESTful服务,可以保存Person个对象:

@RequestMapping(value = "/save", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody ResponseEntity<Person> savePerson(@RequestBody Person person) {
    try {
        person = personService.save(person);
        return new ResponseEntity<Person>(person, HttpStatus.OK);
    } catch (Exception e) {
        Person p = null;
        return new ResponseEntity<Person>(p, HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

尝试merge Person对象时出现以下错误:

  

16:02:58,472警告   [org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver]   (默认任务-11)无法读取HTTP消息:   org.springframework.http.converter.HttpMessageNotReadableException:   无法阅读文件:N / A在[来源:   java.io.PushbackInputStream@7583d44c; line:29,column:3](通过   reference chain:com.jobs.spring.domain.Person [“blockedPersons”]);   嵌套异常是   com.fasterxml.jackson.databind.JsonMappingException:N / A at [来源:   java.io.PushbackInputStream@7583d44c; line:29,column:3](通过   参考链:com.jobs.spring.domain.Person [“blockedPersons”])

我猜是因为它谈到了“reference chain”,我可能会有一些递归错误。或者由于某种原因,它正在努力将Java解析为JSON对象。

如果有人可以提供建议,我将不胜感激。

更多信息:

Person.java

@Entity
@Table(name = "person")
@XmlRootElement(name = "person")
public class Person extends AbstractDomain<Long> {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, orphanRemoval = true)
    @JoinTable(name = "person_blocked", joinColumns = {
            @JoinColumn(name = "PER_ID", referencedColumnName = "ID") }, inverseJoinColumns = {
                    @JoinColumn(name = "BLOCK_ID", referencedColumnName = "ID", unique = true) })
    private Set<BlockedPerson> blockedPersons = null;

    ...
}

BlockedPerson.java

@Entity
@Table(name = "blocked_person")
@XmlRootElement(name = "blocked_person")
public class BlockedPerson extends AbstractDomain<Integer> {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "ID", unique = true, nullable = false)
    private Integer id;

    @Column(name = "BLOCKED_PER_ID", nullable = false)
    private Long blockedPersonId;

    @XmlElement
    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    @XmlElement
    public Long getBlockedPersonId() {
        return blockedPersonId;
    }

    public void setBlockedPersonId(Long blockedPersonId) {
        this.blockedPersonId = blockedPersonId;
    }

}

1 个答案:

答案 0 :(得分:0)

解决方案

上述错误的共鸣是因为我在Person上的setter方法中遇到异常,它在null对象上执行以下操作。

this.blockedPersons.clear();

修正:

变化:

private Set<BlockedPerson> blockedPersons = null;

为:

private Set<BlockedPerson> blockedPersons = new HashSet<BlockedPerson>();