[英]JAX-RS (Jersey) creates related object instead of null
問題很簡單,但是有點難以解釋。
我有這樣的REST服務:
@Path("categories")
@RequestScoped
public class CategoryResource {
@Inject
CategoriesFacade dao;
@PUT
@Consumes("application/json")
public void putJson(Categories content) {
System.err.println(content.toString()); // <-- ?????
dao.edit(content);
}
// ....
}
和這樣的實體對象:
@XmlRootElement
public class Categories implements Serializable {
@Id
@Column(name = "CATEGORY_ID", unique = true, nullable = false, precision = 5)
private Integer categoryId;
@Column(name = "NAME")
private String name;
@JoinColumn(name = "PARENT_ID", referencedColumnName = "CATEGORY_ID")
@ManyToOne
private Categories parentId;
// ....
}
這是http請求有效負載:
PUT http://localhost:8080/api/categories
Data: {"categoryId":"7162","name":"test","parentId":null}
這是我在@PUT
請求中獲得的Categories對象(請參閱標有????的行):
Categories{
categoryId=7162,
name=test,
parentId=Categories{categoryId=null, name=null, parentId=null}
}
因此,正如您在此處看到的那樣,為parentId
分配了空的Categories
對象,這樣我就收到了ValidationException,因為name
不能為null。
任何想法如何使Jersey都可以給我這種對象,所以parentId的null值就可以了:
Categories{
categoryId=7162,
name=test,
parentId=null
}
在客戶端站點上對對象進行字符串化(例如,如果客戶端在JavaScropt上,則使用JSON.stringify
方法)。
休息法制作
@PUT
@Consumes("application/json")
public void putJson(String content) {
並將json字符串轉換為對象(例如,使用google json)
Categories cont = new com.google.gson.Gson().fromJson(content, Categories.class);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.