Retrieving values from nested JSON Object

后端 未结 6 1286
星月不相逢
星月不相逢 2020-12-02 19:37

I\'ve got JSON file, which I want to parse. The JSON file (\"myfile\") has format as follows:

{
    \"LanguageLevels\": {
        \"1\": \"Początkujący\",
           


        
6条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-02 19:57

    Try this, you can parse nested JSON

    public static String getJsonValue(String jsonReq, String key) {
            JSONObject json = new JSONObject(jsonReq);
            boolean exists = json.has(key);
            Iterator keys;
            String nextKeys;
            String val = "";
            if (!exists) {
                keys = json.keys();
                while (keys.hasNext()) {
                    nextKeys = (String) keys.next();
                    try {
                        if (json.get(nextKeys) instanceof JSONObject) {
                            return getJsonValue(json.getJSONObject(nextKeys).toString(), key);
                        } else if (json.get(nextKeys) instanceof JSONArray) {
                            JSONArray jsonArray = json.getJSONArray(nextKeys);
                            int i = 0;
                            if (i < jsonArray.length()) do {
                                String jsonArrayString = jsonArray.get(i).toString();
                                JSONObject innerJson = new JSONObject(jsonArrayString);
                                return getJsonValue(innerJson.toString(),key);
                            } while (i < jsonArray.length());
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            } else {
                val = json.get(key).toString();
            }
            return val;
        }
    

提交回复
热议问题