You are currently viewing Why am I getting org.json.JSONException: Not a primitive array?

Why am I getting org.json.JSONException: Not a primitive array?

I have this function:

fun getFeed(token: String): Result<Array<Post?>, Exception> { if (token != "") { val (request, response, result) = "https://alles.cx/api/feed" .httpGet() .header("Authorization", token.toString()) .response() when (result) { is Result.Success -> { println("Result success") try { val responseJSON = JSONObject(String(response.data)) if (!responseJSON.has("err")) { println("Has no error") var feedArray = arrayOfNulls<Post>(0) println("HERE?") var feed = JSONArray(responseJSON["feed"]) // <-----ERROR HERE println("not here") println("Made to the for") for (i in 0 until feed.length()) { println("For $i") val jsonObject = feed.getJSONObject(i) var imageURL: URL? = null if (jsonObject.has("image")) { imageURL = URL(jsonObject["image"].toString()) } feedArray[i] = Post( jsonObject.getString("id"), User(jsonObject.getJSONObject("author").getString("id"), jsonObject.getJSONObject("author").getString("username"), jsonObject.getJSONObject("author").getString("name")), jsonObject.getString("createdAt"), jsonObject.getInt("replyCount"), jsonObject.getInt("score"), jsonObject.getString("content"), null, imageURL, jsonObject.getInt("vote") ) println("Added post $i") } println(feedArray) return Result.Success(feedArray) } else { println("yes error") return Result.Failure(Exception(responseJSON["err"].toString())) } } catch(e: Exception) { return Result.Failure(e) } } is Result.Failure -> { return Result.Failure(Exception(result.component2()?.localizedMessage)) } } } else { return Result.Failure(Exception("badAuth")) } } 

An error is occurring on this line. I know this because of the print statements that are in the code:

var feed = JSONArray(responseJSON["feed"]) // <-----ERROR HERE 

This is what the error that is occurring is.

[Failure: org.json.JSONException: Not a primitive array: class org.json.JSONArray] 

This is what the feed object from the get request will look like, just so you have an idea of what it is:

{ "feed": [ { "type": "post", "slug": "equ2ZfaX2UThtkS8DzkXdc", "author": { "id": "00000000-0000-0000-0000-000000000000", "name": "Archie", "username": "archie", "plus": true }, "content": "I know it's quite inactive here atm. But I'm doing tons of stuff behind the scenes - basically rewriting the entire platform from scratch. Micro will be done by the end of the summer.", "image": null, "createdAt": "2020-07-30T20:39:23.000Z", "score": 5, "vote": 0, "replyCount": 0, "hasParent": false } ] } 

What could possibly be going wrong here. I am using Fuel for the request, but I don’t think that is the problem

submitted by /u/randomtempaccount123
[link] [comments]