问题:
Jersey在接收客户端提交的json数据时提示400 (Bad Request), 服务端没有任何提示.
场景:
客户端
URL:
POST http://127.0.0.1:8080/itart-blog/api/blog/ 400 (Bad Request)
json:
{id:"c4089f719e7c2d25af80756be6421ca9", blogTitle: 'IT Art Test', blogContent:"Test Content", "category": "Blog Category"}
注意: “category”: “Blog Category”
服务端:
BlogResource.java
@Component
@Path("blog")
public class BlogResource{
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response insert(BlogBean blog) throws IOException {
ResponseBuilder reponse = Response.ok();
return reponse.build();
}
}
public class BlogBean{
private String blogTitle;
private String blogContent;
private String id;
...
分析:
客户端提交的Json中有一个字段:”category”, BlogBean中不存在这个属性名.
Jersey要求Json字段必须和后台接收对象的属性完全匹配, Json的字段个数可以少于后台对象属性个数, 但是不能多于, 如果Json有字段在后台对象属性中找不到, 就会报400 (Bad Request)
解决方案: 在BlogBean中增加@JsonIgnoreProperties(ignoreUnknown = true).
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown = true)
public class BlogBean{
private String blogTitle;
private String blogContent;
private String id;
...