如何要求所有 field存在于 JSON 中用Gson解析?-问答-阿里云开发者社区-阿里云

开发者社区> 问答> 正文
阿里云
为了无法计算的价值
打开APP
阿里云APP内打开

如何要求所有 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 2102 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
    赞同 展开评论 打赏
问答排行榜
最热
最新
相关电子书
更多
低代码开发师(初级)实战教程
立即下载
阿里巴巴DevOps 最佳实践手册
立即下载
冬季实战营第三期:MySQL数据库进阶实战
立即下载