Spring Rest POST Json请求体Content type不受支持。

70
当我尝试使用 post 方法发布新对象时,RequestBody 无法识别 contentType。Spring 已经被配置了,并且 POST 方法可以与其他对象一起工作,但是不能与这个特定的对象一起工作。
org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/json;charset=UTF-8' not supported

如果我尝试改变请求体对象并发送同样的请求,它能够正常工作。


如果您没有设置Content type=application/json,则会出现略有不同的错误。 - Vishal Maral
Jackson反序列化器可能会出现问题。请参考链接 - Pratik Chaudhari
由于具有多个字段getter可能会出现问题。请参考链接 - Pratik Chaudhari
17个回答

1

这看起来是一个老的线程,但如果有人仍然在努力,我已经按照Thibaut所说的解决了问题。

避免拥有两个setter POJO类,我为特定属性有两个setter,第一个在常规setter中,另一个在构造函数中。在删除构造函数中的一个之后,它就可以工作了。


1
请在实体类构造函数中指定@JsonProperty,如下所示。
......
......
......

 @JsonCreator
 public Location(@JsonProperty("sl_no") Long sl_no, 
          @JsonProperty("location")String location,
          @JsonProperty("location_type") String 
          location_type,@JsonProperty("store_sl_no")Long store_sl_no) {
  this.sl_no = sl_no;
  this.location = location;
  this.location_type = location_type;
  this.store_sl_no = store_sl_no;
 } 
.......
.......
.......

我应该从com.fasterxml.jackson.annotation.*导入JsonProperty吗? - Marco Ottina

1

当我将此作为外键使用时,我遇到了同样的问题。

@JsonBackReference
@ManyToOne(cascade = {CascadeType.PERSIST, CascadeType.DETACH},fetch = FetchType.EAGER)
@JoinColumn(name = "user_id")
private User user;

然后我移除了@JsonBackReference注解。之后上述问题得到了解决。


0
尝试添加Jackson依赖。
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>2.9.3</version>
    </dependency>

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-annotations</artifactId>
        <version>2.9.3</version>
    </dependency>

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.9.3</version>
        <exclusions>
            <exclusion>
                <artifactId>jackson-annotations</artifactId>
                <groupId>com.fasterxml.jackson.core</groupId>
            </exclusion>
        </exclusions>
    </dependency>

0
在我的情况下,控制器中的函数被注释为:
 @PatchMapping(path = "/{machineGroupName}", consumes = "application/json-patch+json")

当我移除了“Consumes”参数后,它就正常工作了。


0

我曾经遇到过同样的问题,根本原因是在使用自定义反序列化器时没有默认构造函数。


0

只需添加请求头

Content-Type: application/json

对我有用。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接