Search code examples
androidhttpurlconnection

json exception with primitive array


I'm making a call to my localhost, of course with all permissions in place for this android app. Any advice on the json parsing from a string

fun findAll(): ArrayList<User>? {
    val url = URL("http:///10.0.2.2:8080/employees")
    val connection = url.openConnection() as HttpURLConnection
    connection.setRequestProperty("Accept", "application/json");

    var users = arrayListOf<User>()
    (if (connection.responseCode == 200) connection.inputStream else connection.errorStream).use { stream ->
        BufferedReader(InputStreamReader(stream)).use { reader ->
            var line: String?
            val response = StringBuffer()

            while ((reader.readLine().also { line = it }) != null) {
                response.append(line)
            }

            
            val jsonArray = JSONArray(response)
            for (i in 0 until jsonArray.length()) {
                val user = jsonArray.getJSONObject(i)
            }
        }
    }

    return users
}

user data class

data class User(var id: Long?, var first: String?, var last: String?): Parcelable 

problem is at this line

val jsonArray = JSONArray(response)

org.json.JSONException: Not a primitive array: class java.lang.StringBuffer


Solution

  • From Android Documentation:

    public JSONArray (Object array)
    

    Creates a new JSONArray with values from the given primitive array.

    Root cause

    val jsonArray = JSONArray(response)
    

    The response is an instance of StringBuffer not an array, that why the compiler throws the error.

    Solution

    Use the JSONArray(String) constructor instead.

    val jsonArray = JSONArray(response.toString())