我们的REST API接收一些JSON对象输入,其中某些字段必须不为null。这些可以是String / Integer,甚至可以是其他一些类实例作为参考。
我们正在尝试寻找一种方法来强制这些字段不为null,而不是在API中进行null检查的正确方法。当前:
if (myObject.getSomeOtherObject() == null) throw new SomeException();
我们想要的是这样的:
class MyObject{ @Required OtherObject someOtherObject; // ... }
我们尝试了3件事:
1)升级到杰克逊2.0.6,并使用注释com.fasterxml.jackson.annotation.JsonProperty但是,这似乎不起作用。找到了这些参考:http : //jira.codehaus.org/browse/JACKSON-767
2)扩展JsonDeserializer来检查null,但是问题在于它甚至没有在null输入上执行。
public class NotNullDeserializer<T> extends JsonDeserializer<T> { @Override public T deserialize(JsonParser jsonparser, DeserializationContext deserializationcontext) throws IOException, JsonProcessingException { ParameterizedType superClass = (ParameterizedType) getClass().getGenericSuperclass(); Class<T> type = (Class<T>) superClass.getActualTypeArguments()[0]; T t = jsonparser.readValueAs(type); if (t == null){ String classNameField = type.getName(); String field = jsonparser.getCurrentName(); throw new WrongInputException("The field '"+field+"' of type '"+classNameField+"' should not be null."); } return t; } } public class NotNullAddressDeserializer extends NotNullDeserializer<Address> { } @JsonDeserialize(using=NotNullAddressDeserializer.class) Address to;
3)编写我们自己的@Required注释并尝试使用ResourceFilter进行检查,但看来我无法从ContainerRequest中获取实际对象,即使可以,也无法确定如何在中执行null引用的深入检查object.otherObject.someObject.fieldNotNullable
@Required
object.otherObject.someObject.fieldNotNullable
private class Filter implements ResourceFilter, ContainerRequestFilter { private final ArrayList<String> requiredParameters; protected Filter() { requiredParameters = null; } protected Filter(ArrayList<String> requiredParameters) { this.requiredParameters = requiredParameters; } @Override public ContainerRequestFilter getRequestFilter() { return this; } @Override public ContainerResponseFilter getResponseFilter() { return null; } @Override public ContainerRequest filter(ContainerRequest request) { if (requiredParameters != null && requiredParameters.size() > 0) { MultivaluedMap<String, String> params = request.getQueryParameters(); params.putAll(request.getFormParameters()); StringBuffer missingParams = new StringBuffer(); for (String reqParam : requiredParameters) { List<String> paramValues = params.get(reqParam); if (paramValues == null || paramValues != null && paramValues.size() == 0) missingParams.append(reqParam + ","); } if (missingParams.length() > 0) throw new WrongInputException("Required parameters are missing: " + missingParams); } return request; } }
JAX-RS很好地将反序列化与验证分离开来,即,杰克逊在 设计上 没有将值强制为的机制non- null,等等。相反,您可以使用BeanValidation:
non- null
javax.validation:validation-api
provided
javax.validation.constraints.NotNull
有关更多详细信息,请转到此处。