How to iterate over a JSONObject?

后端 未结 16 1878
孤街浪徒
孤街浪徒 2020-11-22 04:17

I use a JSON library called JSONObject (I don\'t mind switching if I need to).

I know how to iterate over JSONArrays, but when I parse JSO

16条回答
  •  逝去的感伤
    2020-11-22 04:48

    I made my small method to log JsonObject fields, and get some stings. See if it can be usefull.

    object JsonParser {
    
    val TAG = "JsonParser"
     /**
     * parse json object
     * @param objJson
     * @return  Map
     * @throws JSONException
     */
    @Throws(JSONException::class)
    fun parseJson(objJson: Any?): Map {
        val map = HashMap()
    
        // If obj is a json array
        if (objJson is JSONArray) {
            for (i in 0 until objJson.length()) {
                parseJson(objJson[i])
            }
        } else if (objJson is JSONObject) {
            val it: Iterator<*> = objJson.keys()
            while (it.hasNext()) {
                val key = it.next().toString()
                // If you get an array
                when (val jobject = objJson[key]) {
                    is JSONArray -> {
                        Log.e(TAG, " JSONArray: $jobject")
                        parseJson(jobject)
                    }
                    is JSONObject -> {
                        Log.e(TAG, " JSONObject: $jobject")
                        parseJson(jobject)
                    }
                    else -> {
                        Log.e(TAG, " adding to map: $key $jobject")
                        map[key] = jobject.toString()
                    }
                }
            }
        }
        return map
    }
    }
    

提交回复
热议问题