开发者社区> 问答> 正文

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

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

展开
收起
蛮大人123 2016-03-10 10:01:14 2279 0
1 条回答
写回答
取消 提交回答
  • 我说我不帅他们就打我,还说我虚伪

    直接用反射检测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);
    }
    2019-07-17 18:56:55
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
神龙云服务器产品及技术深度解析 立即下载
弹性创造价值:基于ECS的最佳性价比实践解析 立即下载
又快又稳:阿里云下一代虚拟交换机解析 立即下载

相关镜像