java - spring boot mvc - 不支持内容类型 'application/json;charset=UTF-8'

标签 java spring spring-mvc spring-boot

this spring boot project POST(使用 Postman)新的 Item 资源时出现错误

Resolving exception from handler 
     [public com.example.demo.resource.Item com.example.demo.controller.ItemController.addItem(com.example.demo.resource.Item)]: 
     org.springframework.web.HttpMediaTypeNotSupportedException: 
     Content type 'application/json;charset=UTF-8' not supported

在请求正文中,我复制了从 GET 请求中获得的现有 Item 之一(并更改了 id项目名称)

    // Request body:
    {
        "id": 10, // also tried without id field as it's autogenerated
        "itemName": "milk",
        "cart": {
            "id": 1
        }
    }

我确保我在 Item 类中有正确的 getter 和 setter(因为这是一个 known issue )

@Entity
@Table(name="items")
@Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)
@JsonIdentityInfo(
          generator = ObjectIdGenerators.PropertyGenerator.class, 
          property = "id")
public class Item
{
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "item_id")
    private long id;

    @Column(name="item_name")
    private String itemName;

    @ManyToOne
    @JoinColumn(name = "cart_id", nullable=false)
    @JsonManagedReference
    private Cart cart;

   //setters and getters
}

这也是 Cart 类,Item 与它具有多对一 关系

@Entity
@Table(name="carts")
@JsonIdentityInfo(
          generator = ObjectIdGenerators.PropertyGenerator.class, 
          property = "id")
public class Cart 
{
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "cart_id")
    private long id;

    @OneToMany(mappedBy = "cart")
    @JsonBackReference
    private Set<Item> items;

    //setters and getters
}

这是ItemController

@RestController
public class ItemController 
{
    private static final Logger LOG = LoggerFactory.getLogger(ItemController.class);

    @Autowired ItemDao dao;

    @GetMapping("items")
    public List<Item> getAll()
    {
        List<Item> res = new ArrayList<>();
        dao.findAll().forEach(res::add);
        return res;
    }

    @PostMapping("items")
    public Item addItem(@RequestBody Item item)
    {
        return dao.save(item);
    }

    @GetMapping("items/{item_id}")
    public Item getItemById(@PathVariable("item_id") long item_id)
    {
        Item item = dao.findById(item_id).get();
        LOG.info(" ---------------- Retrieved item: {}", item.toString());
        return item;
    }
}

编辑

我刚刚注意到前面似乎还有另一个错误:

Failed to evaluate Jackson deserialization for type [[simple type, class com.example.demo.resource.Item]]: com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot handle managed/back reference 'defaultReference': back reference type (java.util.Set) not compatible with managed type (com.example.demo.resource.Item)

这是完整的错误:

2018-02-27 11:03:09.836  WARN 9640 --- [nio-9200-exec-1] .c.j.MappingJackson2HttpMessageConverter : Failed to evaluate Jackson deserialization for type [[simple type, class com.example.demo.resource.Item]]: com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot handle managed/back reference 'defaultReference': back reference type (java.util.Set) not compatible with managed type (com.example.demo.resource.Item)
2018-02-27 11:03:09.837  WARN 9640 --- [nio-9200-exec-1] .c.j.MappingJackson2HttpMessageConverter : Failed to evaluate Jackson deserialization for type [[simple type, class com.example.demo.resource.Item]]: com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot handle managed/back reference 'defaultReference': back reference type (java.util.Set) not compatible with managed type (com.example.demo.resource.Item)
2018-02-27 11:03:09.838 DEBUG 9640 --- [nio-9200-exec-1] .w.s.m.m.a.ServletInvocableHandlerMethod : Failed to resolve argument 0 of type 'com.example.demo.resource.Item'

org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/json;charset=UTF-8' not supported

感谢帮助

最佳答案

您不能将 Collection、Map、Array 或 enumeration 用作 @JsonBackReference

引用链接:https://fasterxml.github.io/jackson-annotations/javadoc/2.2.0/com/fasterxml/jackson/annotation/JsonBackReference.html .

尝试交换 @JsonBackReference@JsonManagedReference。它应该有效。

关于java - spring boot mvc - 不支持内容类型 'application/json;charset=UTF-8',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49005609/

相关文章:

java - LWJGL 中的平铺引擎

java - 从 2 字节大端读取 16 位整数

spring - 如何将带有 angular 2 前端(angular-cli 构建)的 spring-boot webapp 部署到 Tomcat?

java - 复制具有关联角色的新用户

java - JSTL 变量未显示

java - 如何正确编码以下 URL

java - 无法定位元素: {"method" :"id" ,"selector" :"sysPublishDateDate"}

spring - 注册过滤器时 "addMappingForServletNames()"的含义是什么?

java - spring boot 用户和 session mongo

java - 有没有办法禁止将类用作 spring bean?