Default JSON to Object mapping not working

一世执手 提交于 2020-01-15 08:45:42

问题


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!


回答1:


Try adding the @RequestBody annotation:

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


来源:https://stackoverflow.com/questions/13406362/default-json-to-object-mapping-not-working

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!