tintin
tintin

Reputation: 5867

Default JSON to Object mapping not working

I would like to perform a POST of JSON message and want to do conversion to Employee Object. The JSON message is {"employee":{"id":2231,"name":"jeffarry2231","niNumber":"SN10KTL"}} .

The Employee Object

public class Employee {
    private Long id;
    private String name;
    private String niNumber;
    ...
}

The EmployeeController

@Controller
public class EmployeeController {

   @RequestMapping(value = "/employee/add/", method = RequestMethod.POST)
    public void addEmployee(Employee employee){
       System.out.println(employee.getName());
    }
}

The RestTemplate which is Posting the request is

@Test
public void postMethod() {
    RestTemplate restTemplate = new RestTemplate();
    String jsonEmployee = "{'id':2231,'name':'jeffarry2231','niNumber':'SN10KTL'}}";

    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(newArrayList(MediaType.APPLICATION_JSON));
    HttpEntity<String> requestEntity = new HttpEntity<String>(jsonEmployee, headers);
    restTemplate.exchange("http://localhost:8080/employee/add/", POST, requestEntity, String.class);
}

The applicationContext.xml has

<mvc:annotation-driven/>

I'm expecting the MappingJacksonHttpMessageConverter to be used by default but it dosen't seem to convert, not sure what I'm missing here!

Upvotes: 2

Views: 486

Answers (1)

nickdos
nickdos

Reputation: 8414

Try adding the @RequestBody annotation:

@RequestMapping(value = "/employee/add/", method = RequestMethod.POST)
public void addEmployee(@RequestBody Employee employee){
   System.out.println(employee.getName());
}

Upvotes: 3

Related Questions