forked from Kotlin/kotlinx.serialization
-
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Support serialization of collections that are not lists
So far there was an implicit assumption hard-coded that collections are always lists. However, sets are also collections, and can be serialized to JSON arrays just like lists. This change allows to serialize generic collections independently of the concrete implementation. Fixes Kotlin#1421.
- Loading branch information
1 parent
1175416
commit 96f475e
Showing
2 changed files
with
53 additions
and
11 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
41 changes: 41 additions & 0 deletions
41
formats/json/commonTest/src/kotlinx/serialization/features/CollectionSerializerTest.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,41 @@ | ||
/* | ||
* Copyright 2017-2022 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. | ||
*/ | ||
|
||
package kotlinx.serialization.features | ||
|
||
import kotlinx.serialization.* | ||
import kotlinx.serialization.builtins.* | ||
import kotlinx.serialization.json.Json | ||
import kotlinx.serialization.test.* | ||
import kotlin.test.* | ||
|
||
class CollectionSerializerTest { | ||
|
||
@Serializable | ||
data class CollectionWrapper( | ||
val collection: Collection<String> | ||
) | ||
|
||
@Test | ||
fun testListJson() { | ||
val list = listOf("foo", "bar", "foo", "bar") | ||
|
||
val string = Json.encodeToString(CollectionWrapper(list)) | ||
assertEquals("""{"collection":["foo","bar","foo","bar"]}""", string) | ||
|
||
val wrapper = Json.decodeFromString<CollectionWrapper>(string) | ||
assertEquals(list, wrapper.collection) | ||
} | ||
|
||
@Test | ||
fun testSetJson() { | ||
val set = setOf("foo", "bar", "foo", "bar") | ||
|
||
val string = Json.encodeToString(CollectionWrapper(set)) | ||
assertEquals("""{"collection":["foo","bar"]}""", string) | ||
|
||
val wrapper = Json.decodeFromString<CollectionWrapper>(string) | ||
assertEquals(set.toList(), wrapper.collection) | ||
} | ||
} |