【问题标题】:spring boot maps null properties to POJO from JSON post request from angular2spring boot 将 null 属性映射到来自 angular2 的 JSON 发布请求的 POJO
【发布时间】:2017-07-26 07:21:07
【问题描述】:

在对该主题进行了大量研究后,我决定在这里提问。我正在获取 POJO/Model 的所有 null 属性,该属性应该从我从 Angular 2 前端发布的 JSON 中获取值。这是其余控制器方法:

@RequestMapping(value = "/employees/update",  method = RequestMethod.POST, consumes = "application/json")
    public String allEmployees( @RequestBody Employee emp){
        return "";
    } 

以下是POJO/Model/Hibernate Entity:

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(nullable = false, updatable = false)
private Long id;

private String firstname;
private String lastname;
private String department;

public Employee(){}

public Long getId() {
    return id;
}
public void setId(Long id) {
    this.id = id;
}
public String getFirstname() {
    return firstname;
}
public void setFirstname(String firstname) {
    this.firstname = firstname;
}
public String getLastname() {
    return lastname;
}
public void setLastname(String lastname) {
    this.lastname = lastname;
}
public String getDepartment() {
    return department;
}
public void setDepartment(String department) {
    this.department = department;
}

以下是Angular 2的Service方法:

updateEmployee(emp:Employee){
  let url: string = "http://localhost:8080/api/employees/update";
  let headers = new Headers();
  headers.append('Content-Type', 'application/json');
  return  this.http.post(url, {emp}, {headers: headers, withCredentials: true }).map(res => res.json());
}

以及 Angular 2 的 Employee 接口:

export interface Employee{
  id: number;
  firstname: string;
  lastname: string;
  department: string;
}

我做错了什么?我搜索了类似的问题,但没有找到适用于我的案例。谢谢!

【问题讨论】:

  • 尝试用@ResponseBody注释方法
  • 还是一样...所有属性都为空
  • 我刚刚解决了它,实际上它不是映射,因为我在 emp 变量周围放置了大括号。非常感谢您的帮助

标签: json spring rest angular spring-boot


【解决方案1】:

您需要在发送之前序列化 javascript 对象。试试:

this.http.post(url, JSON.stringify(emp), {headers: headers, withCredentials: true }).map(res => res.json());

【讨论】:

  • 谢谢,但我已经试过了,没有任何区别...我相信问题出在后端而不是前端。
  • 那么,有效载荷是否确定正确发送?检查浏览器控制台的网络选项卡。
  • 我刚刚解决了它,实际上它不是映射,因为我在 emp 变量周围放置了大括号。非常感谢您的帮助
【解决方案2】:

尝试用@ResponseBody注释方法

会变成:

@ResponseBody
@RequestMapping(value = "/employees/update",  method = RequestMethod.POST, consumes = "application/json")
    public String allEmployees( @RequestBody Employee emp){
        return "";
    } 

【讨论】:

  • 参数emp还是一样。它的所有属性都设置为 null。
猜你喜欢
  • 2021-12-15
  • 1970-01-01
  • 2016-12-21
  • 2016-10-20
  • 2019-09-27
  • 2019-11-25
  • 1970-01-01
  • 2016-06-27
  • 2021-09-15
相关资源
最近更新 更多