猿问

Gson 解析 JSON,如何要求所有 field 存在于 JSON 中?

例如我有一个类 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 没有类似的东西么?


湖上湖
浏览 711回答 3
3回答

largeQ

直接用反射检测json是否有该字段不就行了。class A {&nbsp; &nbsp; String a;&nbsp; &nbsp; String b;&nbsp; &nbsp; List<B> list;}class B{...}private static void checkJson(JSONObject json, Class<?> clazz) {&nbsp; &nbsp; Field[] fields = clazz.getDeclaredFields();&nbsp; &nbsp; for (Field field : fields) {&nbsp; &nbsp; &nbsp; &nbsp; if (!json.has(field.getName())) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; throw new JsonParseException();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; // 遍历数组&nbsp; &nbsp; &nbsp; &nbsp; Type type = field.getGenericType();&nbsp; &nbsp; &nbsp; &nbsp; if (type instanceof ParameterizedType) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Type[] types = ((ParameterizedType) type).getActualTypeArguments();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Type t = types[0];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; JSONArray array = json.getJSONArray(field.getName());&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for (int i = 0; i < array.length(); i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Object childJSON = array.get(i);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (childJSON instanceof JSONObject) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; checkJson((JSONObject) childJSON, (Class) t);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}public static void main(String[] args){&nbsp; &nbsp; A a = new A();&nbsp; &nbsp; ...&nbsp; &nbsp; String json = new Gson().toJson(a);&nbsp; &nbsp; checkJson(new JSONObject(json), A.class);}

GCT1015

貌似没找到,可以自己通过业务逻辑进行控制,在序列化之后得到的Object进行空判断即可
随时随地看视频慕课网APP

相关分类

Java
我要回答