简体   繁体   English

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

[英]spring boot mvc - Content type 'application/json;charset=UTF-8' not supported

In this spring boot project I get an error when POST ing (using Postman) a new Item resource 这个春季启动项目中,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

In the request body I copied one of the existing Item s that I got from a GET request (and changed the id and itemName ) 在请求正文中,我复制了一个从GET请求获得的现有Item (并更改了iditemName

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

I made sure that I have the correct getters and setters in the Item class (as this is a known issue ) 我确保在Item类中有正确的getter和setter(因为这是一个已知问题

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

Here is also the Cart class to which Item has a many-to-one relationship 这里也是Item类与many-to-one关系的Cart

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

This is the ItemController 这是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;
    }
}

EDIT 编辑

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)

Here is the full error: 这是完整的错误:

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

Thanks for the help 谢谢您的帮助

You can not use Collection, Map, Array or enumeration as @JsonBackReference . 您不能将Collection, Map, Array or enumeration用作@JsonBackReference

Refer the link : https://fasterxml.github.io/jackson-annotations/javadoc/2.2.0/com/fasterxml/jackson/annotation/JsonBackReference.html . 请参阅链接: https//fasterxml.github.io/jackson-annotations/javadoc/2.2.0/com/fasterxml/jackson/annotation/JsonBackReference.html

Try interchanging @JsonBackReference and @JsonManagedReference . 尝试交换@JsonBackReference@JsonManagedReference It should work. 它应该工作。

I got the same issue. 我遇到了同样的问题。 //@JsonBackReference dosen't matter. // @ JsonBackReference无关紧要。 Delete //@JsonManagedReference, it works. 删除// @ JsonManagedReference,它可以工作。

Many: 许多:

@JsonBackReference
@OneToMany(targetEntity=Device.class, mappedBy="detectUnit") 
private List<Device> devices;

One: 一:

@ManyToOne
private DetectUnit detectUnit;

POST method works for both. POST方法适用于两者。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Spring 启动 controller 调用不支持内容类型 'application/json;charset=UTF-8' - Content type 'application/json;charset=UTF-8' not supported with Spring boot controller call Spring Boot - 不支持内容类型“application/x-www-form-urlencoded;charset=UTF-8” - Spring Boot - Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported 不支持内容类型 'application/json;charset=UTF-8' - Content type 'application/json;charset=UTF-8' not supported Spring Rest 应用程序中的“不支持内容类型‘application/json;charset=UTF-8’” - "Content type 'application/json;charset=UTF-8' not supported" in Spring Rest application 当我尝试将 JSON 发送到 Spring 时,不支持内容类型“application/json;charset=UTF-8” - Content type 'application/json;charset=UTF-8' not supported, when i try send JSON to Spring 内容类型 &#39;application/json;charset=UTF-8&#39; - Content type 'application/json;charset=UTF-8' 不支持 Spring Boot 内容类型 'multipart/form-data;boundary=------------------------#;charset=UTF-8' - Spring Boot Content type 'multipart/form-data;boundary=--------------------------#;charset=UTF-8' not supported 不支持Netflix Feign内容类型&#39;pplication / json; charset = UTF-8&#39; - Netflix Feign Content type 'pplication/json;charset=UTF-8' not supported 使用 XML 数据时出错 内容类型 'application/xml;charset=utf-8' not supported spring - Error in consuming XML data Content type 'application/xml;charset=utf-8' not supported spring 其余API POST内容类型&#39;application / json; charset = UTF-8&#39;不支持 - Rest API POST Content type 'application/json;charset=UTF-8' not supported
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM