1. 程式人生 > >android json在不確定key時,獲取key跟value的值

android json在不確定key時,獲取key跟value的值

動態獲取key和value

private void check(){
        String s = "{" +
                "\"com.pm.zse\": {" +
                "\"check\": false," +
                "\"own\": true," +
                "\"complete\": true" +
                "}," +
                "\"com.om.cme\": {" +
                "\"loaded\": false," +
                "\"complete\": false," +
                "\"com\": \"whoami\"" +
                "}" +
                "}";
        try {
            JSONObject jsonObject = new JSONObject(s);
            Iterator<String> objs =  jsonObject.keys();
            String key;
            while (objs.hasNext()){
                key = objs.next();
                System.err.println("key: "+key);
                JSONObject jo = jsonObject.getJSONObject(key);
                Iterator<String> ks =  jo.keys();
                String k;
                while (ks.hasNext()){
                    k = ks.next();
                    System.err.println("k: "+k);
                    String v = jo.getString(k);
                    System.err.println("v: "+v);
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }