我正在制作休息网络服务我的代码是:
@Path("/add")
@POST
@Produces(MediaType.APPLICATION_JSON)
public Response addMembers(List<GroupMemberMap> groupMemberMaps){
String message = "";
System.out.println("Inside addMembers of class "+this.toString());
try {
DBConnection.insertMembers(groupMemberMaps);
message = "Member(s) added";
return Response.status(Status.CREATED)
.entity(message)
.type(MediaType.TEXT_PLAIN)
.build();
} catch(SQLException sqle){
System.out.println("addMembers catch sqle");
message = "A problem occured while adding members : "+sqle.getMessage();
return Response.status(Status.INTERNAL_SERVER_ERROR)
.entity(message)
.type(MediaType.TEXT_PLAIN)
.build();
}
catch (Exception e) {
// TODO Auto-generated catch block
System.out.println("Inside addMembers catch "+e.getMessage());
message = "A problem occured while adding members : "+e.getMessage();
return Response.status(Status.INTERNAL_SERVER_ERROR)
.entity(message)
.type(MediaType.TEXT_PLAIN)
.build();
}
}
但是当我用这个Json调用它时:
[
{
"userId":"3",
"groupId":"4"
}
]
我正在接受以下例外:
javax.servlet.ServletException:org.codehaus.jackson.map.exc.UnrecognizedPropertyException:无法识别的字段“userId”(类com.tazligen.model.GroupMemberMap),在[来源:org.apache.catalina]中未标记为可忽略.connector.CoyoteInputStream @ 14ec141; line:2,column:15](通过参考链:com.tazligen.model.GroupMemberMap [“userId”])
我的GrouMemberMap模型类是:
package com.tazligen.model;
@XmlRootElement
public class GroupMemberMap {
private String userId;
private String groupId;
public String getUserid() {
return userId;
}
public void setUserid(String userId) {
this.userId = userId;
}
public String getGroupId() {
return groupId;
}
public void setGroupId(String groupId) {
this.groupId = groupId;
} }
我尝试了另外一种方法:
@Path("/membertest")
@POST
public String test(List<User> members){
return "Test subresource members working";
}
与json
[{
"userId":"3",
"userName":"John"}]
但这项工作正常:/
需要有人帮忙。
答案 0 :(得分:7)
在查看GroupMemberMap
Class:
UserId
的Getter-Setter不正确。此外,您可以添加可选@JsonIgnoreProperties
以忽略所有其他未知字段。
以下是更正后的代码段:
package com.tazligen.model;
@XmlRootElement
@JsonIgnoreProperties(ignoreUnknown = true)
public class GroupMemberMap {
@JsonProperty("userId")
private String userId;
@JsonProperty("groupId")
private String groupId;
/* Add Constructor */
public GroupMemberMap() {}
/* Corrected Name */
public String getUserId() {
return userId;
}
/* Corrected Name */
public void setUserId(String userId) {
this.userId = userId;
}
public String getGroupId() {
return groupId;
}
public void setGroupId(String groupId) {
this.groupId = groupId;
}
}
答案 1 :(得分:-1)
只需修改userId和groupId public
。默认情况下,Jackson处理公共成员变量。
我认为JsonIgnoreProperties并不是解决方案,因为它被用来忽略它无法识别的内容。
public String userId;
public String groupId;