Skip to content

Commit 2f7f3dd

Browse files
committed
fixed incomplete JSONObject.toMap
Also added JSONArray.toList() and a few more JSON tests
1 parent 09ab331 commit 2f7f3dd

File tree

2 files changed

+48
-13
lines changed

2 files changed

+48
-13
lines changed

OneSignalSDK/onesignal/core/src/main/java/com/onesignal/common/JSONObjectExtensions.kt

Lines changed: 37 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package com.onesignal.common
22

33
import org.json.JSONArray
44
import org.json.JSONObject
5+
import org.json.JSONObject.NULL
56

67
/**
78
* Retrieve an [Int] from the [JSONObject] safely.
@@ -95,15 +96,46 @@ fun JSONObject.safeJSONObject(name: String): JSONObject? {
9596

9697
/**
9798
* Create a [Map] from the [JSONObject].
99+
* Supports nested JSONObjects and JSONArrays.
98100
*/
99-
fun JSONObject.toMap(): Map<String, Any> {
100-
val map = mutableMapOf<String, Any>()
101-
101+
fun JSONObject.toMap(): MutableMap<String, Any?> {
102+
val results: MutableMap<String, Any?> = HashMap()
102103
for (key in this.keys()) {
103-
map[key] = this[key]
104+
val value = this[key]
105+
results[key] =
106+
if (NULL.equals(value)) {
107+
null
108+
} else if (value is JSONObject) {
109+
value.toMap()
110+
} else if (value is JSONArray) {
111+
value.toList()
112+
} else {
113+
value
114+
}
104115
}
116+
return results
117+
}
105118

106-
return map
119+
/**
120+
* Create a [List] from the [JSONArray].
121+
* Supports nested JSONObjects and JSONArrays.
122+
*/
123+
fun JSONArray.toList(): List<Any?>? {
124+
val size = this.length()
125+
val results: MutableList<Any?> = ArrayList(size)
126+
for (i in 0 until size) {
127+
val element = this.opt(i)
128+
if (NULL.equals(element)) {
129+
results.add(null)
130+
} else if (element is JSONArray) {
131+
results.add(element.toList())
132+
} else if (element is JSONObject) {
133+
results.add(element.toMap())
134+
} else {
135+
results.add(element)
136+
}
137+
}
138+
return results
107139
}
108140

109141
/**

OneSignalSDK/onesignal/core/src/test/java/com/onesignal/common/JSONObjectExtensionsTest.kt

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -42,14 +42,17 @@ class JSONObjectExtensionsTest : DescribeSpec({
4242
)
4343
}
4444

45-
it("supports JSONArray") {
46-
val test =
47-
JSONObject()
48-
.put("MyArray", JSONArray().put("String"))
49-
test.toMap() shouldBe
50-
mapOf(
51-
"MyArray" to listOf("String"),
52-
)
45+
describe("JSONArray") {
46+
it("supports empty") {
47+
val test = JSONObject().put("MyArray", JSONArray())
48+
test.toMap() shouldBe
49+
mapOf("MyArray" to emptyList<Any>())
50+
}
51+
it("supports one item") {
52+
val test = JSONObject().put("MyArray", JSONArray().put("String"))
53+
test.toMap() shouldBe
54+
mapOf("MyArray" to listOf("String"))
55+
}
5356
}
5457

5558
it("supports JSONObject") {

0 commit comments

Comments
 (0)