为什么break不会结束while循环?

时间:2015-11-14 10:56:39

标签: java json

我有一些json:

{"continue":{"continue":"||","rvcontinue":"20021126020855|1194424"},"query":{"pages":{"468997":{"ns":0,"revisions":[{"revid":445765,"comment":"","user":"Nate Silva","parentid":0,"timestamp":"2002-11-26T02:01:24Z"}],"pageid":468997,"title":"Vodafone"}}}}

我想以递归方式解析json的时间戳:

private static LocalDate getTimeStamp(JSONObject json) throws IOException {
        Iterator<?> keys = json.keys();
        LocalDate ld = null;

        // iterate recursively over all keys from the JSON until current key is
        // timestamp
        while (keys.hasNext()) {
            String key = (String) keys.next();
            if (key.equals("timestamp")) {
                // timezone does not matter, as we just want to extract the date
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern(
                        "yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.ENGLISH);
                ld = LocalDate.parse(json.get(key).toString(), formatter);
                System.out.println(ld);
                break;
            }
            // if the current value is another JSON object, call setTimeStamp
            // with value as param
            else if (json.get(key) instanceof JSONObject) {
                getTimeStamp((JSONObject) json.get(key));
            }
            // handle current value being JSON array
            else if (json.get(key) instanceof JSONArray) {
                JSONArray jarray = (JSONArray) json.get(key);
                for (int i = 0; i < jarray.length(); i++) {
                    if (jarray.get(i) instanceof JSONObject) {
                        getTimeStamp((JSONObject) jarray.get(i));
                    }
                }
            }

        }
        System.out.println(ld);
        return ld;
    }

我尝试过调试它,但是在调用break之后我不知道调用该方法的原因。它返回null而不是时间戳,尽管它到达代码的那一部分。

2 个答案:

答案 0 :(得分:3)

"timestamp"键嵌套在您的JSON中,因此需要对您的方法进行一些递归调用才能获得它。

进行递归调用时,应使用这些调用返回的值。

变化

getTimeStamp((JSONObject) json.get(key));

ld = getTimeStamp((JSONObject) json.get(key));
if (ld != null) return ld;

并更改

getTimeStamp((JSONObject) jarray.get(i));

ld = getTimeStamp((JSONObject) jarray.get(i));
if (ld != null) return ld;

答案 1 :(得分:3)

您的代码返回null,因为您忽略了递归调用的结果。您应该将它们存储在变量中,如果不是null,则返回它:

while (keys.hasNext() && ld == null) {
    ...
    else if (json.get(key) instanceof JSONObject) {
        ld = getTimeStamp((JSONObject) json.get(key));
    }
    // handle current value being JSON array
    else if (json.get(key) instanceof JSONArray) {
        JSONArray jarray = (JSONArray) json.get(key);
        for (int i = 0; i < jarray.length(); i++) {
            if (jarray.get(i) instanceof JSONObject) {
                ld = getTimeStamp((JSONObject) jarray.get(i));
                if (ld != null) 
                    break;
            }
        }
    }
}

请注意,由于您要查找第一个时间戳,while循环应在ld变为非null时停止。