gpt4 book ai didi

json - JAX-RS/Jersey ".get(Integer.class)"和单个 JSON 原语(整数)值?

转载 作者:行者123 更新时间:2023-12-01 10:00:55 25 4
gpt4 key购买 nike

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

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

欢迎任何想法!

最佳答案

这是一个 recognized bug in 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 对象中,由objects simple type name - 但请注意,如果使用此选项,所有生成的 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}
Deserialized Value: 42

参见 this answer有关如何在 JAX-RS 环境中检索和配置 ObjectMapper 实例的详细信息。

关于json - JAX-RS/Jersey ".get(Integer.class)"和单个 JSON 原语(整数)值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16408950/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com