简体   繁体   中英

Mapping incoming JSON to a class in spring boot

I'm struggling to understand why I'm getting the following error when I call my spring boot end point

{
  "timestamp": 1489573322678,
  "status": 406,
  "error": "Not Acceptable",
  "exception": "org.springframework.web.HttpMediaTypeNotAcceptableException",
  "message": "Could not find acceptable representation",
  "path": "/quotes"
}

This is the request that I'm sending to the server

POST /quotes HTTP/1.1
Host: localhost:8080
tamid: 5
Content-Type: application/json
Cache-Control: no-cache
Postman-Token: 94370a3f-6165-106f-f27f-44a44093e0d5

{
    "test": "works"
}

I would like the incoming JSON request body to map to a java class I have defined. Here is the class.

@Embedded
public class QuoteVersion {

    private String test;

    public String getTest() {
        return test;
    }

    public void setTest(String test) {
        this.test = test;
    }

    public void validate() {
    }
}

I'm using the @Embedded annotation for use with a mongodb mapping library that I'm hoping is unrelated to the issue I'm facing

Here is the controller method

@RequestMapping(
    path = "/quotes",
    method = RequestMethod.POST,
    headers = "Accept=application/json",
    produces = "application/json"
)
public @ResponseBody QuoteStatus create (@RequestHeader(value = "tamid") String tamId,
                                         @RequestBody QuoteVersion firstQuoteVersion) {
    // final QuoteVersion firstQuoteVersion = this.quoteFactory.createQuoteVersion(incomingQuote);
    final User currentUser = User.getFromTamId(tamId);
    currentUser.can(Permissions.CREATE_QUOTE);
    firstQuoteVersion.validate();
    final Quote newQuote = new Quote();
    newQuote.addVersion(firstQuoteVersion);
    this.dataRepository.save(newQuote);
    QuoteStatus qs = new QuoteStatus(newQuote);
    return qs;
}

I'm guessing that Spring Boot for some reason does not understand how to map the incoming payload to the class I have defined but I have no idea how to fix the issue. Thanks in advance for any help you may have to offer.

Spring clearly indicates this problem:

HttpMediaTypeNotAcceptableException

This means that in your content-type header you provided the wrong information or made a syntactical mistake. Try putting there something like application/json .

Also

Make sure the other end will accept it. You currently only accepting requests with an accept header with value application/json . I don't think that is what you want.

So either remove that requirement or add this header to the request.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM