我有一个使用以下方法的JAX-RS WebService:
@Path("/myrest")
public class MyRestResource {
...
@GET
@Path("/getInteger")
@Produces(APPLICATION_JSON)
public Integer getInteger() {
return 42;
}使用下面的代码片段访问时:
@Test
public void testGetPrimitiveWrapers() throws IOException {
// this works:
assertEquals(new Integer(42), new ObjectMapper().readValue("42", Integer.class));
// that fails:
assertEquals(new Integer(42), resource().path("/myrest/getInteger").get(Integer.class));
}我得到了以下异常:
com.sun.jersey.api.client.ClientResponse getEntity
SEVERE: A message body reader for Java class java.lang.Integer, and Java type class java.lang.Integer, and MIME media type application/json was not found
com.sun.jersey.api.client.ClientResponse getEntity
SEVERE: The registered message body readers compatible with the MIME media type are: application/json
...问题只是返回单个原始值(int/boolean)或它们的包装类。返回其他POJO类不是问题,所以我猜关于JSONConfiguration.FEATURE_POJO_MAPPING和JAXB注释的所有答案在这里都不适用。或者,如果我不能访问返回类型的类源代码,我应该使用哪个注释来描述返回类型?
使用ngrep,我可以验证webservice只返回字符串"42“。根据规范,这是一个有效的JSON“值”,但不是一个有效的JSON“文本”。那么我的问题是在客户端还是在服务器端?
根据http://tugdualgrall.blogspot.de/2011/09/jax-rs-jersey-and-single-element-arrays.html的说法,我尝试激活JSONConfiguration natural/badgerfish,但是没有成功(ngrep仍然只显示"42")。这是正确的道路吗?
任何想法都很受欢迎!
发布于 2013-05-07 13:29:06
这是一个recognized bug in Jackson,它被吹捧为一个功能(在我看来是错误的)。为什么我认为它是一个bug?因为虽然序列化可以工作,但反序列化肯定不行。
在任何情况下,都不能从当前的返回类型生成有效的JSON,所以我建议创建一个包装类:
class Result<T> {
private T data;
// constructors, getters, setters
}
@GET
@Path("/getInteger")
@Produces(APPLICATION_JSON)
public Result<Integer> getInteger() {
return new Result<Integer)(42);
}你可以选择包装根值,它会自动将你的数据封装在一个顶层的Alternatively,对象中,以对象的简单类型名为关键字--但请注意,如果使用这个选项,所有生成的JSON都将被包装(不仅仅是基元):
final ObjectMapper mapper = new ObjectMapper()
.configure(SerializationFeature.WRAP_ROOT_VALUE, true)
.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
final String serializedJson = mapper.writeValueAsString(42);
final Integer deserializedVal = mapper.readValue(serializedJson,
Integer.class);
System.out.println(serializedJson);
System.out.println("Deserialized Value: " + deserializedVal);输出:
{“整型”:42}
反序列化的值: 42
有关如何在JAX-RS环境中检索和配置ObjectMapper实例的详细信息,请参阅this answer。
https://stackoverflow.com/questions/16408950
复制相似问题