2

我想执行 JSON 消息的 POST 并希望转换为 Employee Object。JSON 消息是 {"employee":{"id":2231,"name":"jeffarry2231","niNumber":"SN10KTL"}} .

员工对象

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

员工控制器

@Controller
public class EmployeeController {

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

发布请求的 RestTemplate 是

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

applicationContext.xml 有

<mvc:annotation-driven/>

我希望 MappingJacksonHttpMessageConverter 默认使用,但它似乎没有转换,不确定我在这里缺少什么!

4

1 回答 1

3

尝试添加@RequestBody注释:

@RequestMapping(value = "/employee/add/", method = RequestMethod.POST)
public void addEmployee(@RequestBody Employee employee){
   System.out.println(employee.getName());
}
于 2012-11-16T02:57:03.383 回答