summaryrefslogtreecommitdiff
path: root/guide/example/example-json-20.kt
diff options
context:
space:
mode:
authorLeonid Startsev <sandwwraith@users.noreply.github.com>2021-08-17 22:47:24 +0300
committerGitHub <noreply@github.com>2021-08-17 22:47:24 +0300
commitfa569a8f4f5475a18b546c09a27bdd959bd0099b (patch)
treed6d04008625d924113a62c0e10dfd731cbde864a /guide/example/example-json-20.kt
parentd00bff2bbda69a17083480ec9daaaad5a54d2b42 (diff)
downloadkotlinx.serialization-fa569a8f4f5475a18b546c09a27bdd959bd0099b.tar.gz
Documentation for 'explicitNulls' feature (#1634)
Fixes #1619 Co-authored-by: Sergey.Shanshin <sergey.shanshin@jetbrains.com>
Diffstat (limited to 'guide/example/example-json-20.kt')
-rw-r--r--guide/example/example-json-20.kt37
1 files changed, 37 insertions, 0 deletions
diff --git a/guide/example/example-json-20.kt b/guide/example/example-json-20.kt
new file mode 100644
index 00000000..d12547d7
--- /dev/null
+++ b/guide/example/example-json-20.kt
@@ -0,0 +1,37 @@
+// This file was automatically generated from json.md by Knit tool. Do not edit.
+package example.exampleJson20
+
+import kotlinx.serialization.*
+import kotlinx.serialization.json.*
+
+import kotlinx.serialization.descriptors.*
+import kotlinx.serialization.encoding.*
+
+data class UnknownProject(val name: String, val details: JsonObject)
+
+object UnknownProjectSerializer : KSerializer<UnknownProject> {
+ override val descriptor: SerialDescriptor = buildClassSerialDescriptor("UnknownProject") {
+ element<String>("name")
+ element<JsonElement>("details")
+ }
+
+ override fun deserialize(decoder: Decoder): UnknownProject {
+ // Cast to JSON-specific interface
+ val jsonInput = decoder as? JsonDecoder ?: error("Can be deserialized only by JSON")
+ // Read the whole content as JSON
+ val json = jsonInput.decodeJsonElement().jsonObject
+ // Extract and remove name property
+ val name = json.getValue("name").jsonPrimitive.content
+ val details = json.toMutableMap()
+ details.remove("name")
+ return UnknownProject(name, JsonObject(details))
+ }
+
+ override fun serialize(encoder: Encoder, value: UnknownProject) {
+ error("Serialization is not supported")
+ }
+}
+
+fun main() {
+ println(Json.decodeFromString(UnknownProjectSerializer, """{"type":"unknown","name":"example","maintainer":"Unknown","license":"Apache 2.0"}"""))
+}