search

Home  >  Q&A  >  body text

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

天蓬老师天蓬老师2767 days ago434

reply all(3)I'll reply

  • 伊谢尔伦

    伊谢尔伦2017-04-17 16:36:22

    Just use reflection to detect whether json has this field.

    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);
    }

    reply
    0
  • 巴扎黑

    巴扎黑2017-04-17 16:36:22

    It seems that it is not found. You can control it by yourself through business logic. Just make a null judgment on the Object obtained after serialization

    reply
    0
  • 迷茫

    迷茫2017-04-17 16:36:22

    You can only write a custom Deserializer. You can refer to stackoverflow. Someone has asked the same question.

    http://stackoverflow.com/questions/3163193/strict-json-parsing-with-googles-gson

    reply
    0
  • Cancelreply