无法将Javascript对象转换为Java Model

时间:2017-03-11 22:04:05

标签: javascript java ajax spring

我的Spring控制器和客户端Javascript代码如下,由于某种原因,Javascript对象无法以Object形式到达Spring控制器。我的控制器代码如下:

@RequestMapping(value = "/addRating", method = RequestMethod.POST, headers = "Accept=application/json")
public EmployeeRating addRating(@ModelAttribute("employeeRating") EmployeeRating employeeRating) {  
    if(employeeRating.getId()==0)
    {
        employeeRatingService.addRating(employeeRating);
    }
    else
    {   
        employeeRatingService.updateRating(employeeRating);
    }

    return employeeRating;
}

我的Javascript代码如下:

$.ajax({
          url: 'https://myrestURL/addRating',
          type: 'POST',
          dataType: 'json',
          data: {
              'id':5,
              'name': 'Name',
              'rating': '1'
          },
          contentType: 'application/json; charset=utf-8',
          success: function (result) {
             // CallBack(result);
             window.alert("Result: " + result);
          },
          error: function (error) {
              window.alert("Error: " + error);
          }
      });

Java中的EmployeeRating对象具有id,name和rating字段,因此没有不匹配。

更新模型类

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

/* 
 * This is our model class and it corresponds to Country table in database
 */
@Entity
@Table(name="EMPLOYEERATING")
public class EmployeeRating {

@Id
@Column(name="id")
@GeneratedValue(strategy=GenerationType.IDENTITY)
int id;

@Column(name="name")
String name;    

@Column(name="rating")
long rating;

public EmployeeRating() {
    super();
}
public EmployeeRating(int i, String name,long rating) {
    super();
    this.id = i;
    this.name = name;
    this.rating=rating;
}
public int getId() {
    return id;
}
public void setId(int id) {
    this.id = id;
}
public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public long getRating() {
    return rating;
}
public void setRating(long rating) {
    this.rating = rating;
}   

}

1 个答案:

答案 0 :(得分:1)

contentType是您要发送的数据类型,因此application/json;默认值为application/x-www-form-urlencoded; charset=UTF-8

如果您使用application/json,则必须使用JSON.stringify()才能发送JSON个对象。

JSON.stringify()将javascript对象转换为json文本并将其存储在字符串中。

$.ajax({
      url: 'https://myrestURL/addRating',
      type: 'POST',
      dataType: 'json',
      data: JSON.stringify({
          'id':5,
          'name': 'Name',
          'rating': '1'
      }),
      contentType: 'application/json; charset=utf-8',
      success: function (result) {
         // CallBack(result);
         window.alert("Result: " + result);
      },
      error: function (error) {
          window.alert("Error: " + error);
      }
  });