Skip to content

Commit e382853

Browse files
committed
Kotlin: Implement ObjectSerialize recursively
1 parent aa9f3ec commit e382853

File tree

2 files changed

+45
-4
lines changed

2 files changed

+45
-4
lines changed

glean-core/android/src/main/java/mozilla/telemetry/glean/private/ObjectMetricType.kt

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,12 @@ interface ObjectSerialize {
2020
fun intoSerializedObject(): String
2121
}
2222

23+
fun Boolean.intoSerializedObject(): String = Json.encodeToString(this)
24+
25+
fun Int.intoSerializedObject(): String = Json.encodeToString(this)
26+
27+
fun String.intoSerializedObject(): String = Json.encodeToString(this)
28+
2329
/**
2430
* This implements the developer facing API for the object metric type.
2531
*

glean-core/android/src/test/java/mozilla/telemetry/glean/private/ObjectMetricTypeTest.kt

Lines changed: 39 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,6 @@ import org.junit.Rule
1919
import org.junit.Test
2020
import org.junit.runner.RunWith
2121

22-
@Serializable
2322
data class BalloonsObject(
2423
var items: MutableList<BalloonsObjectItem> = mutableListOf(),
2524
) : ObjectSerialize {
@@ -40,14 +39,50 @@ data class BalloonsObject(
4039
element: BalloonsObjectItem,
4140
) = items.set(index, element)
4241

43-
override fun intoSerializedObject(): String = Json.encodeToString(items)
42+
override fun intoSerializedObject(): String {
43+
var json = buildString {
44+
append("[")
45+
var first = true
46+
for (item in items) {
47+
if (!first) {
48+
append(",")
49+
}
50+
first = false
51+
append(item.intoSerializedObject())
52+
}
53+
append("]")
54+
}
55+
return json
56+
}
4457
}
4558

46-
@Serializable
4759
data class BalloonsObjectItem(
4860
var colour: String? = null,
4961
var diameter: Int? = null,
50-
)
62+
) : ObjectSerialize {
63+
override fun intoSerializedObject(): String {
64+
var data: MutableList<String> = mutableListOf()
65+
this.colour?.let { colour ->
66+
val elem = buildString {
67+
append("\"colour\":")
68+
append(colour.intoSerializedObject())
69+
}
70+
data.add(elem)
71+
}
72+
this.diameter?.let { diameter ->
73+
val elem = buildString {
74+
append("\"diameter\":")
75+
append(diameter.intoSerializedObject())
76+
}
77+
data.add(elem)
78+
}
79+
return buildString {
80+
append("{")
81+
append(data.joinToString(","))
82+
append("}")
83+
}
84+
}
85+
}
5186

5287
@RunWith(AndroidJUnit4::class)
5388
class ObjectMetricTypeTest {

0 commit comments

Comments
 (0)