Spring Boot MVC-不支持内容类型'application/json; charset = UTF-8' [英] spring boot mvc - Content type 'application/json;charset=UTF-8' not supported

查看:760
本文介绍了Spring Boot MVC-不支持内容类型'application/json; charset = UTF-8'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此春季启动项目中,当POST ing(使用Postman)时,我收到一条错误消息)新的Item资源

In this spring boot project I get an error when POSTing (using Postman) a new Item resource

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之一(并更改了iditemName)

In the request body I copied one of the existing Items that I got from a GET request (and changed the id and itemName)

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

我确保在Item类中具有正确的getter和setter方法(因为这是

I made sure that I have the correct getters and setters in the Item class (as this is a 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
}

这里也是Item与它具有many-to-one关系的Cart

Here is also the Cart class to which Item has a many-to-one relationship

@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;
    }
}

编辑

我刚刚发现前面似乎还有另一个错误:

I just noticed that there seems to be another error preceding:

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 or enumeration用作@JsonBackReference.

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

尝试互换@JsonBackReference@JsonManagedReference.应该可以.

Try interchanging @JsonBackReference and @JsonManagedReference. It should work.

这篇关于Spring Boot MVC-不支持内容类型'application/json; charset = UTF-8'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆