例如我有一个类 class A { String a; String b; }
,我用 Gson 去解析一段 JSON { "b": "naive" }
可以得到一个 A
的实例,其 a
为 null
。
但我想要求目标类中所有 field 必须存在于 JSON 中,否则就抛出 JsonParseException
。譬如这个例子中的 JSON 里没有 a
属性,就直接作为解析失败,抛异常,是否可能做到?
貌似 Jackson 有 FAIL_ON_IGNORED_PROPERTIES
这个 flag 可以用。Gson 没有类似的东西么?
这个只能写一个自定义的Deserializer, 可以参看stackoverflow,有人问过同样的问题。
http://stackoverflow.com/questions/3163193/strict-json-parsing-with-googles-gson
直接用反射检测json是否有该字段不就行了。
class A {
String a;
String b;
List<B> list;
}
class B{...}
private static void checkJson(JSONObject json, Class<?> clazz) {
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
if (!json.has(field.getName())) {
throw new JsonParseException();
}
// 遍历数组
Type type = field.getGenericType();
if (type instanceof ParameterizedType) {
Type[] types = ((ParameterizedType) type).getActualTypeArguments();
Type t = types[0];
JSONArray array = json.getJSONArray(field.getName());
for (int i = 0; i < array.length(); i++) {
Object childJSON = array.get(i);
if (childJSON instanceof JSONObject) {
checkJson((JSONObject) childJSON, (Class) t);
}
}
}
}
}
public static void main(String[] args){
A a = new A();
...
String json = new Gson().toJson(a);
checkJson(new JSONObject(json), A.class);
}
貌似没找到,可以自己通过业务逻辑进行控制,在序列化之后得到的Object进行空判断即可