Reputation: 1695
I know that this question is asked hundreds of time, I've checked more than 30 answer and none worked for me.
I'm running a unit test in android studio using Kotlin. I'm trying to build a JSONObject
using a String
.
The method I'm using to build a simple json object is always throwing Cannot evaluate org.json.JSONObject.toString()
.
The string I'm using definitely have a valid Json format.
Is this a bug in android or what??
Here's the method I'm using:
fun createTaskJson(): JSONObject {
val jsonString =
"{\"id\":138,\"title\":\"G0102-025\",\"type\":\"New Land Evaluation\",\"taskCreationDate\":\"28/01/2020\",\"taskDeliveryDate\":\"02/02/2020\",\"taskCreationTime\":\"05:15 AM\"}"
val realJson = JSONObject(jsonString)
return realJson
}
UPDATE 1:
Please note that also creating an empty JSONObject
will throw the same error !!
UPDATE 2:
After checking the stacktrace, I've found the following error:
Method toString in org.json.JSONObject not mocked.
I've googled it and the solution was to add the following configuration into my build.gradle
file:
testOptions {
unitTests.returnDefaultValues = true
}
But adding this made the returned JSONObject
null instead of throwing an exception, even though my string is formatted correctly.
Upvotes: 0
Views: 2169
Reputation: 1695
After the updates mentioned in the question above. And after lots of searching. I found out the following:
The solution was in adding the following line into build.gradle
file:
implementation group: 'org.json', name: 'json', version: '20190722'
I don't know why, but it's like android have an object with names JSONArray
and JSONObject
but when adding the implementation
to the build.gradle
file. It handles JSONObject
and JSONArray
in another way.
Because after adding the statement to the gradle file, the following warning will be giving by android:
json
define classes that conflict with classes now provided by Android
Upvotes: 3