我想让Java失败到Json转换,如果任何Java属性为null,注释为@required,
我可以使用以下方法实现这一目标.如果您发现任何问题,请与我们联系:
class requiredKeyAdapterFactory implements TypeAdapterFactory {
public TypeAdapter create(Gson gson,TypeToken type) {
final TypeAdapter delegate = gson.getDelegateAdapter(this,type);
return new TypeAdapter() {
@Override
public void write(JsonWriter out,T value) throws IOException {
if (value != null) {
Field[] fields = value.getClass().getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
if (fields[i]
.isAnnotationPresent(required.class)) {
validateNullValue(value,fields[i]);
}
}
}
delegate.write(out,value);
}
private void validateNullValue(T value,Field field) {
field.setAccessible(true);
Class t = field.getType();
Object v = null;
try {
v = field.get(value);
} catch (IllegalArgumentException | IllegalAccessException e) {
throw new IllegalArgumentException(e);
}
if (t == boolean.class && Boolean.FALSE.equals(v)) {
throw new IllegalArgumentException(field + " is null");
} else if (t.isPrimitive()
&& ((Number) v).doubleValue() == 0) {
throw new IllegalArgumentException(field + " is null");
} else if (!t.isPrimitive() && v == null) {
throw new IllegalArgumentException(field + " is null");
}
}
@Override
public T read(JsonReader in) throws IOException {
return delegate.read(in);
}
};
}
}
requiredKeyAdapterFactory requiredKeyAdapterFactory = new requiredKeyAdapterFactory();
Gson gson = new GsonBuilder().registerTypeAdapterFactory(requiredKeyAdapterFactory)
.create();
这很有效