【问题标题】:Content type 'application/json;charset=UTF-8' not supported when post to restController发布到 restController 时不支持内容类型 'application/json;charset=UTF-8'
【发布时间】:2019-12-22 16:00:12
【问题描述】:

这个问题只发生在这个控制器上,因为我在模型中添加了一个自我关系。

我在其他帖子和谷歌中阅读和搜索,任何解决方案似乎都有效。

我尝试设置@JsonIdentityInfo,添加@JsonBackReference 和@JsonManagedReference,颠倒此标签的顺序,将消耗添加到rest 方法,但一切正常

型号:

@Entity

@JsonIdentityInfo(
  generator = ObjectIdGenerators.PropertyGenerator.class, 
  property = "code")

@Table (name = "EP7_TRS_CODIGOS")
public class Code implements Serializable {

    private static final long serialVersionUID = 2L;

    @Id
    @Column (name = "COD_CODIGO")
    private String code;

    @Column (name = "DES_CODIGO")
    private String description;

    @Column (name = "COD_TIPO")
    private String type;

    @JsonManagedReference
    @ManyToOne
    @JoinColumn (name = "ID_ORIGEN", referencedColumnName = "ID_ORIGEN")
    private Origin origin;

    @JsonBackReference
    @ManyToOne
    @JoinColumn (name="COD_CODIGO_OBJ", referencedColumnName = "COD_CODIGO")
    private Code parent;

    @JsonManagedReference
    @OneToMany (mappedBy = "parent", fetch = FetchType.LAZY)
    private List<Code> sons;

控制器:

@PostMapping(value = "/code",
    consumes = MediaType.APPLICATION_JSON_UTF8_VALUE,
    produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
public ResponseEntity<Code> saveOrUpdateCode (@RequestHeader HttpHeaders httpHeaders, @RequestBody Code code){
    logger.info(">>>> Entra en el controlador saveOrUpdateCode");
    if (httpHeaders == null || !authorized(httpHeaders)) {
        logger.error(">>>> Error de autentificacion");
        return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
    } 
    return new ResponseEntity<>(cs.save(code), HttpStatus.CREATED);
}

起源类

@Entity
// @JsonIdentityInfo(
//   generator = ObjectIdGenerators.PropertyGenerator.class, 
//   property = "id")
@Table (name = "EP7_TRS_ORIGEN")
public class Origin implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @Column (name = "ID_ORIGEN")
    private int id;

    @Column (name = "DES_ORIGEN")
    private String description;

    @Column (name = "COD_TIPO")
    private String type;

    @JsonBackReference
    @OneToMany (targetEntity=Code.class, mappedBy="origin", fetch = FetchType.LAZY) 
    private List<Code> codes;

【问题讨论】:

    标签: java spring-boot


    【解决方案1】:

    发送 post 请求时,您需要添加标头 Content-type 和值 application/json。此外,您应该从 Origin 类中删除 @JsonManagedReference

    【讨论】:

    • 您好,感谢您的回复。我还没有添加 Content-type: application/json but not work
    • 我添加了它。我认为问题是代码中的自我关系,这个类在实现这种关系之前就已经工作了。我试图用这么多没有结果的更改来管理它,我开始认为它必须被删除并以更好的方式更改数据模型
    • 我试过你的代码,但没有 Origin 字段,它对我有用。
    • 您好,耶稣,请查看编辑后的答案,它可以解决您的问题。
    猜你喜欢
    • 2018-07-24
    • 2015-11-01
    • 1970-01-01
    • 2016-12-07
    • 1970-01-01
    • 2018-08-06
    • 1970-01-01
    • 2015-03-26
    • 2019-12-16
    相关资源
    最近更新 更多