3

我有一个具有以下方法的 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 我可以验证 Web 服务仅返回字符串“42”。根据规范,这是一个有效的 JSON“值”,但不是一个有效的 JSON“文本”。那么我的问题是在客户端还是服务器端?

我尝试根据http://tugdualgrall.blogspot.de/2011/09/jax-rs-jersey-and-single-element-arrays.html激活 JSONConfiguration natural/badgerfish但没有成功(ngrep 仍然只显示“42” )。那会是正确的道路吗?

任何想法表示赞赏!

4

1 回答 1

7

这是Jackson 中公认的错误,它被吹捧为(在我看来是错误的)一个功能。为什么我认为它是一个错误?因为虽然序列化有效,但反序列化绝对不行。

在任何情况下,都无法从您当前的返回类型生成有效的 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);
}

或者,您可以选择包装根值,这将自动将您的数据封装在顶级 JSON 对象中,由对象简单类型名称作为键 - 但请注意,如果使用此选项,所有生成的 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);

输出:

{"Integer":42}
反序列化值:42

有关如何在 JAX-RS 环境中检索和配置实例的详细信息,请参阅此答案。ObjectMapper

于 2013-05-07T05:29:05.653 回答