1

I have an CRUD Controller in a Spring MVC API.

This is my create method:

    @Override
    @JsonView(ApiView.FormView.class)
    @RequestMapping(method = RequestMethod.POST, consumes = ApiMediaType.jsonContentType, produces = ApiMediaType.jsonContentType)
    public ApiResponse create(@RequestBody @Valid Entity entity, BindingResult result) {
        if (result.hasErrors()) return new ApiResponse(result.getAllErrors());
        service.add(entity);
        return new ApiResponse(entity);
    }

This works good.

If I am sending such data to the API, it works

   {
        "email":"user@company.com",
        "password":"secret!",
        "firstName":"John",
        "lastName":"Doe",
        "title":"Mr."
    }

The problem is that I am using Ember JS with Ember Data. My adapter is sending this data:

{
   "data":{
      "attributes":{
         "email":"user@company.com",
         "firstName":"John",
         "lastName":"Doe",
         "title":"Mr.",
      },
      "type":"users"
   }
}

This is not a @Valid User form, that my UserController is expecting in the create method declared below:

public ApiResponse create(@RequestBody @Valid User form, BindingResult result) {}

How can I convert the data that Ember is sending to a User object into my Spring Application ?

Thanks and sorry for my english.

2 Answers2

0

You have to use a MessageConverter and a JacksonMapper that fit your data structure.

Here there are some tutorials

http://magicmonster.com/kb/prg/java/spring/webmvc/jackson_custom.html

http://www.java-allandsundry.com/2014/09/customizing-httpmessageconverters-with.html

http://www.baeldung.com/spring-httpmessageconverter-rest

reos
  • 8,766
  • 6
  • 28
  • 34
0

You forgot the @ResponseBody annotation.

Try this:

@Override
@JsonView(ApiView.FormView.class)
@RequestMapping(method = RequestMethod.POST, consumes = ApiMediaType.jsonContentType, produces = ApiMediaType.jsonContentType)
@ResponseBody    
public ApiResponse create(@RequestBody @Valid Entity entity, BindingResult result) {
    if (result.hasErrors()) return new ApiResponse(result.getAllErrors());
    service.add(entity);
    return new ApiResponse(entity);
}
wilson
  • 627
  • 2
  • 11
  • 24