我使用Jersey构建了一个REST服务,并在AppEngine上部署。该REST服务实现了使用application/json
媒体类型的PUT谓词。数据绑定由Jackson执行。
该谓词消耗一个以JSON格式表示的企业部门关系
{"name":"myEnterprise", "departments":["HR","IT","SC"]}
在客户端,我使用Gson将JSON表示法转换为Java对象。然后,我将该对象传递给我的REST服务,并且它可以正常工作。
问题:
当我的JSON表示法中只有一个项目时
{"name":"myEnterprise", "departments":["HR"]}
服务无法反序列化对象。
ATTENTION: /enterprise/enterprise: org.codehaus.jackson.map.JsonMappingException:
Can not deserialize instance of java.util.ArrayList out of VALUE_STRING token at
[Source: org.mortbay.jetty.HttpParser$Input@5a9c5842; line: 1, column: 2
根据其他用户的报告,解决方法是添加标记ACCEPT_SINGLE_VALUE_AS_ARRAY
(例如,Jersey: Can not deserialize instance of ArrayList out of String)。然而,我没有控制ObjectMapper
,因为在服务端它是由Jackson自动处理的。
问题:
有没有办法在服务端配置ObjectMapper
来启用ACCEPT_SINGLE_VALUE_AS_ARRAY
?使用注释?还是web.xml
?
代码细节:
Java对象:
@XmlRootElement
public class Enterprise {
private String name;
private List<String> departments;
public Enterprise() {}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<String> getDepartments() {
return departments;
}
public void setDepartments(List<String> departments) {
this.departments = departments;
}
}
REST服务端:
@PUT
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Path("/enterprise")
public Response putEnterprise(Enterprise enterprise,
@Context HttpServletRequest req){
...
}
客户端:
...
String jsonString = "{\"name\":\"myEnterprise\", \"departments\":[\"HR\"]}";
Enterprise enterprise = gson.fromJson(jsonString, Enterprise.class);
System.out.println(gson.toJson(enterprise));
response = webResource
.type(MediaType.APPLICATION_JSON)
.put(ClientResponse.class,enterprise);
if (response.getStatus() >= 400) {
throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
}
...