默认 JSON 到对象映射不起作用 [英] Default JSON to Object mapping not working

查看:48
本文介绍了默认 JSON 到对象映射不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想执行 JSON 消息的 POST 并想转换为员工对象.JSON 消息是 {"employee":{"id":2231,"name":"jeffarry2231","niNumber":"SN10KTL"}}.

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"}} .

员工对象

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 是

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

applicationContext.xml 有

The applicationContext.xml has

<mvc:annotation-driven/>

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

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

推荐答案

尝试添加 @RequestBody 注释:

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

这篇关于默认 JSON 到对象映射不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆