我正在使用 Jersy Rest,其中一项要求是从客户端到 REST 端点的输入数量可变,并且 JSON 文档具有 N 个字段。我被要求编写一个 @JsonParam 注释并将输入 json 映射到 Rest Endpoint 方法参数。 类似的东西
public ResultWrapper addToCart(@JsonParam(key="cartId") String cartId)
{
....
}
输入 JSON 可能位于的位置
{
cartId:1233,
custId:123213,
itemId:3344
}
我在类路径中有 jackson,并提供了一个解决方案,其中将整个输入 JSON 映射到 java.util.Map 并使用 map.get(key) 获取值。但他们坚持使用 @JsonParam,因为在映射中没有类型安全,我必须将每个输入解析为相应的类型。
我需要一些关于如何为 @JsonParam 编写与 jersy 一起使用的注释处理器的指导。
最佳答案
下面是一个基于 Jersey 的 1.x InjectableProvder 的示例代码,该代码将值从发布到资源方法的 JSON 字符串注入(inject)到参数中。
注释类:
@Retention(RetentionPolicy.RUNTIME)
public @interface JsonParam {
String key();
}
提供者类:
@Provider
public class JsonParamProvider implements InjectableProvider<JsonParam, Parameter> {
@Override
public ComponentScope getScope() {
return ComponentScope.PerRequest;
}
@Override
public Injectable<Object> getInjectable(ComponentContext ic, final JsonParam jsonParam, Parameter parameter) {
return new AbstractHttpContextInjectable<Object>() {
@Override
public Object getValue(HttpContext c) {
// extract the entity one per request
Map<?, ?> entity = c.getRequest().getEntity(Map.class);
if (entity != null) {
// then store it a request property
c.getProperties().put("requestEntity", entity);
} else {
entity = (Map<?, ?>) c.getProperties().get("requestEntity");
}
if (entity == null) {
return null;
}
return entity.get(jsonParam.key());
}
};
}
}
资源方法声明:
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public String foo(@JsonParam(key = "a") String param1, @JsonParam(key = "b") Integer param2) {
return "Params: " + param1 + " " + param2;
}
关于java - 编写 @JsonParam 注解将请求正文中的 Json 字段映射到方法 args,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23885109/