summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorLeonid Startsev <sandwwraith@gmail.com>2023-11-13 18:03:10 +0100
committerLeonid Startsev <sandwwraith@gmail.com>2023-11-13 18:03:10 +0100
commitb2a05a42d143830d88e6b16bbb4d869dacc727b8 (patch)
tree81aab5460a61368fa9ba5fa01d9ae5d03a949379
parentcf71e0881b284ce8b2d3cf67218869fec4e37d82 (diff)
parentd5bc7f7e27834064e8699ad6c9c39d6dcef039ed (diff)
downloadkotlinx.serialization-b2a05a42d143830d88e6b16bbb4d869dacc727b8.tar.gz
Merge remote-tracking branch 'origin/master' into dev
-rw-r--r--README.md23
-rw-r--r--core/commonMain/src/kotlinx/serialization/ContextualSerializer.kt2
-rw-r--r--docs/serialization-guide.md1
-rw-r--r--docs/serializers.md56
-rw-r--r--formats/README.md5
-rw-r--r--guide/example/example-serializer-16.kt9
-rw-r--r--guide/example/example-serializer-17.kt19
-rw-r--r--guide/example/example-serializer-18.kt34
-rw-r--r--guide/example/example-serializer-19.kt24
-rw-r--r--guide/example/example-serializer-20.kt15
-rw-r--r--guide/example/example-serializer-21.kt31
-rw-r--r--guide/example/example-serializer-22.kt20
-rw-r--r--guide/example/example-serializer-23.kt28
-rw-r--r--guide/test/SerializersTest.kt27
14 files changed, 188 insertions, 106 deletions
diff --git a/README.md b/README.md
index a6269dc1..59f443a2 100644
--- a/README.md
+++ b/README.md
@@ -23,9 +23,8 @@ Kotlin serialization consists of a compiler plugin, that generates visitor code
* [Introduction and references](#introduction-and-references)
* [Setup](#setup)
* [Gradle](#gradle)
- * [Using the `plugins` block](#using-the-plugins-block)
- * [Using `apply plugin` (the old way)](#using-apply-plugin-the-old-way)
- * [Dependency on the JSON library](#dependency-on-the-json-library)
+ * [1) Setting up the serialization plugin](#1-setting-up-the-serialization-plugin)
+ * [2) Dependency on the JSON library](#2-dependency-on-the-json-library)
* [Android](#android)
* [Multiplatform (Common, JS, Native)](#multiplatform-common-js-native)
* [Maven](#maven)
@@ -83,9 +82,13 @@ Make sure you have the corresponding Kotlin plugin installed in the IDE, no addi
### Gradle
-#### Using the `plugins` block
+To set up kotlinx.serialization, you have to do two things:
+1) Add the **[serialization plugin](#1-setting-up-the-serialization-plugin)**.
+2) Add the **[serialization library dependency](#2-dependency-on-the-json-library)**.
-You can set up the serialization plugin with the Kotlin plugin using
+#### 1) Setting up the serialization plugin
+
+You can set up the serialization plugin with the Kotlin plugin using the
[Gradle plugins DSL](https://docs.gradle.org/current/userguide/plugins.html#sec:plugins_block):
Kotlin DSL:
@@ -106,9 +109,10 @@ plugins {
}
```
-> Kotlin versions before 1.4.0 are not supported by the stable release of Kotlin serialization
+> Kotlin versions before 1.4.0 are not supported by the stable release of Kotlin serialization.
-#### Using `apply plugin` (the old way)
+<details>
+ <summary>Using <code>apply plugin</code> (the old way)</summary>
First, you have to add the serialization plugin to your classpath as the other [compiler plugins](https://kotlinlang.org/docs/reference/compiler-plugins.html):
@@ -145,10 +149,11 @@ Then you can `apply plugin` (example in Groovy):
apply plugin: 'kotlin' // or 'kotlin-multiplatform' for multiplatform projects
apply plugin: 'kotlinx-serialization'
```
+</details>
-#### Dependency on the JSON library
+#### 2) Dependency on the JSON library
-After setting up the plugin one way or another, you have to add a dependency on the serialization library.
+After setting up the plugin, you have to add a dependency on the serialization library.
Note that while the plugin has version the same as the compiler one, runtime library has different coordinates, repository and versioning.
Kotlin DSL:
diff --git a/core/commonMain/src/kotlinx/serialization/ContextualSerializer.kt b/core/commonMain/src/kotlinx/serialization/ContextualSerializer.kt
index 53fd4c30..20e9ce1c 100644
--- a/core/commonMain/src/kotlinx/serialization/ContextualSerializer.kt
+++ b/core/commonMain/src/kotlinx/serialization/ContextualSerializer.kt
@@ -29,7 +29,7 @@ import kotlin.reflect.*
* @Serializable
* class ClassWithDate(val data: String, @Contextual val timestamp: Date)
*
- * val moduleForDate = serializersModule(MyISO8601DateSerializer)
+ * val moduleForDate = serializersModuleOf(MyISO8601DateSerializer)
* val json = Json { serializersModule = moduleForDate }
* json.encodeToString(ClassWithDate("foo", Date())
* ```
diff --git a/docs/serialization-guide.md b/docs/serialization-guide.md
index 445d32e3..68ede144 100644
--- a/docs/serialization-guide.md
+++ b/docs/serialization-guide.md
@@ -71,6 +71,7 @@ Once the project is set up, we can start serializing some classes.
* <a name='serializing-3rd-party-classes'></a>[Serializing 3rd party classes](serializers.md#serializing-3rd-party-classes)
* <a name='passing-a-serializer-manually'></a>[Passing a serializer manually](serializers.md#passing-a-serializer-manually)
* <a name='specifying-serializer-on-a-property'></a>[Specifying serializer on a property](serializers.md#specifying-serializer-on-a-property)
+ * <a name='specifying-serializer-for-a-particular-type'></a>[Specifying serializer for a particular type](serializers.md#specifying-serializer-for-a-particular-type)
* <a name='specifying-serializers-for-a-file'></a>[Specifying serializers for a file](serializers.md#specifying-serializers-for-a-file)
* <a name='specifying-serializer-globally-using-typealias'></a>[Specifying serializer globally using typealias](serializers.md#specifying-serializer-globally-using-typealias)
* <a name='custom-serializers-for-a-generic-type'></a>[Custom serializers for a generic type](serializers.md#custom-serializers-for-a-generic-type)
diff --git a/docs/serializers.md b/docs/serializers.md
index 2da17fa4..e6bf78e3 100644
--- a/docs/serializers.md
+++ b/docs/serializers.md
@@ -24,6 +24,7 @@ In this chapter we'll take a look at serializers in more detail, and we'll see h
* [Serializing 3rd party classes](#serializing-3rd-party-classes)
* [Passing a serializer manually](#passing-a-serializer-manually)
* [Specifying serializer on a property](#specifying-serializer-on-a-property)
+ * [Specifying serializer for a particular type](#specifying-serializer-for-a-particular-type)
* [Specifying serializers for a file](#specifying-serializers-for-a-file)
* [Specifying serializer globally using typealias](#specifying-serializer-globally-using-typealias)
* [Custom serializers for a generic type](#custom-serializers-for-a-generic-type)
@@ -713,7 +714,7 @@ because we don't control the `Date` source code. There are several ways to work
### Passing a serializer manually
All `encodeToXxx` and `decodeFromXxx` functions have an overload with the first serializer parameter.
-When a non-serializable class, like `Date`, is the top-level class being serialized we can use those.
+When a non-serializable class, like `Date`, is the top-level class being serialized, we can use those.
```kotlin
fun main() {
@@ -770,6 +771,45 @@ The `stableReleaseDate` property is serialized with the serialization strategy t
<!--- TEST -->
+### Specifying serializer for a particular type
+
+[`@Serializable`][Serializable] annotation can also be applied directly to the types.
+This is handy when a class that requires a custom serializer, such as `Date`, happens to be a generic type argument.
+The most common use case for that is when you have a list of dates:
+
+<!--- INCLUDE
+import java.util.Date
+import java.text.SimpleDateFormat
+
+object DateAsLongSerializer : KSerializer<Date> {
+ override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("Date", PrimitiveKind.LONG)
+ override fun serialize(encoder: Encoder, value: Date) = encoder.encodeLong(value.time)
+ override fun deserialize(decoder: Decoder): Date = Date(decoder.decodeLong())
+}
+-->
+
+```kotlin
+@Serializable
+class ProgrammingLanguage(
+ val name: String,
+ val releaseDates: List<@Serializable(DateAsLongSerializer::class) Date>
+)
+
+fun main() {
+ val df = SimpleDateFormat("yyyy-MM-ddX")
+ val data = ProgrammingLanguage("Kotlin", listOf(df.parse("2023-07-06+00"), df.parse("2023-04-25+00"), df.parse("2022-12-28+00")))
+ println(Json.encodeToString(data))
+}
+```
+
+> You can get the full code [here](../guide/example/example-serializer-16.kt).
+
+```text
+{"name":"Kotlin","releaseDates":[1688601600000,1682380800000,1672185600000]}
+```
+
+<!--- TEST -->
+
### Specifying serializers for a file
A serializer for a specific type, like `Date`, can be specified for a whole source code file with the file-level
@@ -803,7 +843,7 @@ fun main() {
println(Json.encodeToString(data))
}
```
-> You can get the full code [here](../guide/example/example-serializer-16.kt).
+> You can get the full code [here](../guide/example/example-serializer-17.kt).
```text
{"name":"Kotlin","stableReleaseDate":1455494400000}
@@ -857,7 +897,7 @@ fun main() {
}
```
-> You can get the full code [here](../guide/example/example-serializer-17.kt).
+> You can get the full code [here](../guide/example/example-serializer-18.kt).
```text
{"stableReleaseDate":"2016-02-15","lastReleaseTimestamp":1657152000000}
@@ -905,7 +945,7 @@ fun main() {
}
```
-> You can get the full code [here](../guide/example/example-serializer-18.kt).
+> You can get the full code [here](../guide/example/example-serializer-19.kt).
The resulting JSON looks like the `Project` class was serialized directly.
@@ -969,7 +1009,7 @@ fun main() {
To actually serialize this class we must provide the corresponding context when calling the `encodeToXxx`/`decodeFromXxx`
functions. Without it we'll get a "Serializer for class 'Date' is not found" exception.
-> See [here](../guide/example/example-serializer-19.kt) for an example that produces that exception.
+> See [here](../guide/example/example-serializer-20.kt) for an example that produces that exception.
<!--- TEST LINES_START
Exception in thread "main" kotlinx.serialization.SerializationException: Serializer for class 'Date' is not found.
@@ -1028,7 +1068,7 @@ fun main() {
}
```
-> You can get the full code [here](../guide/example/example-serializer-20.kt).
+> You can get the full code [here](../guide/example/example-serializer-21.kt).
```text
{"name":"Kotlin","stableReleaseDate":1455494400000}
```
@@ -1087,7 +1127,7 @@ fun main() {
}
```
-> You can get the full code [here](../guide/example/example-serializer-21.kt).
+> You can get the full code [here](../guide/example/example-serializer-22.kt).
This gets all the `Project` properties serialized:
@@ -1128,7 +1168,7 @@ fun main() {
}
```
-> You can get the full code [here](../guide/example/example-serializer-22.kt).
+> You can get the full code [here](../guide/example/example-serializer-23.kt).
The output is shown below.
diff --git a/formats/README.md b/formats/README.md
index c3e7a5c4..724b06ad 100644
--- a/formats/README.md
+++ b/formats/README.md
@@ -20,8 +20,9 @@ For convenience, they have same `groupId`, versioning and release cycle as core
|--------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------|-------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| Avro | [sksamuel/avro4k](https://github.com/sksamuel/avro4k) <br> `com.sksamuel.avro4k:avro4k` | JVM only | This library allows serialization and deserialization of objects to and from [Avro](https://avro.apache.org). It will read and write from Avro binary or json streams or generate Avro Generic Records directly. It will also generate Avro schemas from data classes. The library allows for easy extension and overrides for custom schema formats, compatiblity with schemas defined outside out of the JVM and for types not supported out of the box. |
| Bson | [jershell/kbson](https://github.com/jershell/kbson) <br> `com.github.jershell:kbson` | JVM only | Allows serialization and deserialization of objects to and from [BSON](https://docs.mongodb.com/manual/reference/bson-types/). |
+| TOML | [Peanuuutz/tomlkt](https://github.com/Peanuuutz/tomlkt) <br> `net.peanuuutz.tomlkt:tomlkt` | all supported platforms | Multiplatform encoder and decoder for [TOML](http://toml.io/) 1.0.0 compliant. This library aims to provide similar API to the official JSON format (such as TomlLiteral, TomlTable), while adding TOML specific features (such as @TomlComment, @TomlMultilineString). |
| TOML | [akuleshov7/ktoml](https://github.com/akuleshov7/ktoml) <br> `com.akuleshov7:ktoml-core` | all supported platforms | Fully Native and Multiplatform Kotlin serialization library for serialization/deserialization of TOML format. This library contains no Java code and no Java dependencies and it implements multiplatform parser, decoder and encoder of TOML. |
-| Minecraft NBT | [BenWoodworth/knbt](https://github.com/BenWoodworth/knbt) <br> `net.benwoodworth.knbt:knbt` | all supported platforms | Implements the [NBT format](https://minecraft.fandom.com/wiki/NBT_format) for kotlinx.serialization, and provides a type-safe DSL for constructing NBT tags. |
+| Minecraft NBT | [BenWoodworth/knbt](https://github.com/BenWoodworth/knbt) <br> `net.benwoodworth.knbt:knbt` | all supported platforms | Implements the [NBT format](https://minecraft.wiki/w/NBT_format) for kotlinx.serialization, and provides a type-safe DSL for constructing NBT tags. |
| MsgPack | [esensar/kotlinx-serialization-msgpack](https://github.com/esensar/kotlinx-serialization-msgpack) <br> `com.ensarsarajcic.kotlinx:serialization-msgpack` | all supported platforms | Allows serialization and deserialization of objects to and from [MsgPack](https://msgpack.org/). |
| SharedPreferences | [EdwarDDay/serialization.kprefs](https://github.com/EdwarDDay/serialization.kprefs) <br> `net.edwardday.serialization:kprefs` | Android only | This library allows serialization and deserialization of objects into and from Android [SharedPreferences](https://developer.android.com/reference/android/content/SharedPreferences). |
| XML | [pdvrieze/xmlutil](https://github.com/pdvrieze/xmlutil) <br> `io.github.pdvrieze.xmlutil:serialization` | all supported platforms | This library allows for reading and writing of XML documents with the serialization library. It is multiplatform, providing both a shared parser/writer for xml as well as platform-specific parsers where available. The library is designed to handle existing xml formats that use features that would not be available in other formats such as JSON. |
@@ -32,4 +33,4 @@ For convenience, they have same `groupId`, versioning and release cycle as core
| android.os.Bundle | [AhmedMourad0/bundlizer](https://github.com/AhmedMourad0/bundlizer) <br> `dev.ahmedmourad.bundlizer:bundlizer-core` | Android | Allow serialization and deserialization of objects to and from [android.os.Bundle](https://developer.android.com/reference/android/os/Bundle). |
| CSV | [hfhbd/kotlinx-serialization-csv](https://github.com/hfhbd/kotlinx-serialization-csv) <br> `app.softwork:kotlinx-serialization-csv` | all supported platforms | Allows serialization and deserialization of CSV files. There are still some limitations (ordered properties). |
| Fixed Length Format | [hfhbd/kotlinx-serialization-csv](https://github.com/hfhbd/kotlinx-serialization-csv) <br> `app.softwork:kotlinx-serialization-flf` | all supported platforms | Allows serialization and deserialization of [Fixed Length Format files](https://www.ibm.com/docs/en/psfa/7.2.1?topic=format-fixed-length-files). Each property must be annotated with `@FixedLength` and there are still some limitations due to missing delimiters. |
-| JSON5 | [xn32/json5k](https://github.com/xn32/json5k) <br> `io.github.xn32:json5k` | JVM, Native | Library for the serialization to and deserialization from [JSON5](https://json5.org) text. |
+| JSON5 | [xn32/json5k](https://github.com/xn32/json5k) <br> `io.github.xn32:json5k` | JVM, Native | Library for the serialization to and deserialization from [JSON5](https://json5.org) text. |
diff --git a/guide/example/example-serializer-16.kt b/guide/example/example-serializer-16.kt
index 157208fd..3db0b7ff 100644
--- a/guide/example/example-serializer-16.kt
+++ b/guide/example/example-serializer-16.kt
@@ -1,4 +1,3 @@
-@file:UseSerializers(DateAsLongSerializer::class)
// This file was automatically generated from serializers.md by Knit tool. Do not edit.
package example.exampleSerializer16
@@ -17,9 +16,13 @@ object DateAsLongSerializer : KSerializer<Date> {
}
@Serializable
-class ProgrammingLanguage(val name: String, val stableReleaseDate: Date)
+class ProgrammingLanguage(
+ val name: String,
+ val releaseDates: List<@Serializable(DateAsLongSerializer::class) Date>
+)
fun main() {
- val data = ProgrammingLanguage("Kotlin", SimpleDateFormat("yyyy-MM-ddX").parse("2016-02-15+00"))
+ val df = SimpleDateFormat("yyyy-MM-ddX")
+ val data = ProgrammingLanguage("Kotlin", listOf(df.parse("2023-07-06+00"), df.parse("2023-04-25+00"), df.parse("2022-12-28+00")))
println(Json.encodeToString(data))
}
diff --git a/guide/example/example-serializer-17.kt b/guide/example/example-serializer-17.kt
index 0ac8dfe8..c5624ed3 100644
--- a/guide/example/example-serializer-17.kt
+++ b/guide/example/example-serializer-17.kt
@@ -1,3 +1,4 @@
+@file:UseSerializers(DateAsLongSerializer::class)
// This file was automatically generated from serializers.md by Knit tool. Do not edit.
package example.exampleSerializer17
@@ -10,27 +11,15 @@ import java.util.Date
import java.text.SimpleDateFormat
object DateAsLongSerializer : KSerializer<Date> {
- override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("DateAsLong", PrimitiveKind.LONG)
+ override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("Date", PrimitiveKind.LONG)
override fun serialize(encoder: Encoder, value: Date) = encoder.encodeLong(value.time)
override fun deserialize(decoder: Decoder): Date = Date(decoder.decodeLong())
}
-object DateAsSimpleTextSerializer: KSerializer<Date> {
- override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("DateAsSimpleText", PrimitiveKind.LONG)
- private val format = SimpleDateFormat("yyyy-MM-dd")
- override fun serialize(encoder: Encoder, value: Date) = encoder.encodeString(format.format(value))
- override fun deserialize(decoder: Decoder): Date = format.parse(decoder.decodeString())
-}
-
-typealias DateAsLong = @Serializable(DateAsLongSerializer::class) Date
-
-typealias DateAsText = @Serializable(DateAsSimpleTextSerializer::class) Date
-
@Serializable
-class ProgrammingLanguage(val stableReleaseDate: DateAsText, val lastReleaseTimestamp: DateAsLong)
+class ProgrammingLanguage(val name: String, val stableReleaseDate: Date)
fun main() {
- val format = SimpleDateFormat("yyyy-MM-ddX")
- val data = ProgrammingLanguage(format.parse("2016-02-15+00"), format.parse("2022-07-07+00"))
+ val data = ProgrammingLanguage("Kotlin", SimpleDateFormat("yyyy-MM-ddX").parse("2016-02-15+00"))
println(Json.encodeToString(data))
}
diff --git a/guide/example/example-serializer-18.kt b/guide/example/example-serializer-18.kt
index cca857c7..9987e822 100644
--- a/guide/example/example-serializer-18.kt
+++ b/guide/example/example-serializer-18.kt
@@ -6,21 +6,31 @@ import kotlinx.serialization.json.*
import kotlinx.serialization.encoding.*
import kotlinx.serialization.descriptors.*
-@Serializable(with = BoxSerializer::class)
-data class Box<T>(val contents: T)
+import java.util.Date
+import java.text.SimpleDateFormat
+
+object DateAsLongSerializer : KSerializer<Date> {
+ override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("DateAsLong", PrimitiveKind.LONG)
+ override fun serialize(encoder: Encoder, value: Date) = encoder.encodeLong(value.time)
+ override fun deserialize(decoder: Decoder): Date = Date(decoder.decodeLong())
+}
-class BoxSerializer<T>(private val dataSerializer: KSerializer<T>) : KSerializer<Box<T>> {
- override val descriptor: SerialDescriptor = dataSerializer.descriptor
- override fun serialize(encoder: Encoder, value: Box<T>) = dataSerializer.serialize(encoder, value.contents)
- override fun deserialize(decoder: Decoder) = Box(dataSerializer.deserialize(decoder))
+object DateAsSimpleTextSerializer: KSerializer<Date> {
+ override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("DateAsSimpleText", PrimitiveKind.LONG)
+ private val format = SimpleDateFormat("yyyy-MM-dd")
+ override fun serialize(encoder: Encoder, value: Date) = encoder.encodeString(format.format(value))
+ override fun deserialize(decoder: Decoder): Date = format.parse(decoder.decodeString())
}
-@Serializable
-data class Project(val name: String)
+typealias DateAsLong = @Serializable(DateAsLongSerializer::class) Date
+
+typealias DateAsText = @Serializable(DateAsSimpleTextSerializer::class) Date
+
+@Serializable
+class ProgrammingLanguage(val stableReleaseDate: DateAsText, val lastReleaseTimestamp: DateAsLong)
fun main() {
- val box = Box(Project("kotlinx.serialization"))
- val string = Json.encodeToString(box)
- println(string)
- println(Json.decodeFromString<Box<Project>>(string))
+ val format = SimpleDateFormat("yyyy-MM-ddX")
+ val data = ProgrammingLanguage(format.parse("2016-02-15+00"), format.parse("2022-07-07+00"))
+ println(Json.encodeToString(data))
}
diff --git a/guide/example/example-serializer-19.kt b/guide/example/example-serializer-19.kt
index 4d7c0729..4622665a 100644
--- a/guide/example/example-serializer-19.kt
+++ b/guide/example/example-serializer-19.kt
@@ -6,17 +6,21 @@ import kotlinx.serialization.json.*
import kotlinx.serialization.encoding.*
import kotlinx.serialization.descriptors.*
-import java.util.Date
-import java.text.SimpleDateFormat
+@Serializable(with = BoxSerializer::class)
+data class Box<T>(val contents: T)
-@Serializable
-class ProgrammingLanguage(
- val name: String,
- @Contextual
- val stableReleaseDate: Date
-)
+class BoxSerializer<T>(private val dataSerializer: KSerializer<T>) : KSerializer<Box<T>> {
+ override val descriptor: SerialDescriptor = dataSerializer.descriptor
+ override fun serialize(encoder: Encoder, value: Box<T>) = dataSerializer.serialize(encoder, value.contents)
+ override fun deserialize(decoder: Decoder) = Box(dataSerializer.deserialize(decoder))
+}
+
+@Serializable
+data class Project(val name: String)
fun main() {
- val data = ProgrammingLanguage("Kotlin", SimpleDateFormat("yyyy-MM-ddX").parse("2016-02-15+00"))
- println(Json.encodeToString(data))
+ val box = Box(Project("kotlinx.serialization"))
+ val string = Json.encodeToString(box)
+ println(string)
+ println(Json.decodeFromString<Box<Project>>(string))
}
diff --git a/guide/example/example-serializer-20.kt b/guide/example/example-serializer-20.kt
index 7ce30e89..38b72e79 100644
--- a/guide/example/example-serializer-20.kt
+++ b/guide/example/example-serializer-20.kt
@@ -6,15 +6,8 @@ import kotlinx.serialization.json.*
import kotlinx.serialization.encoding.*
import kotlinx.serialization.descriptors.*
-import kotlinx.serialization.modules.*
import java.util.Date
import java.text.SimpleDateFormat
-
-object DateAsLongSerializer : KSerializer<Date> {
- override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("Date", PrimitiveKind.LONG)
- override fun serialize(encoder: Encoder, value: Date) = encoder.encodeLong(value.time)
- override fun deserialize(decoder: Decoder): Date = Date(decoder.decodeLong())
-}
@Serializable
class ProgrammingLanguage(
@@ -23,13 +16,7 @@ class ProgrammingLanguage(
val stableReleaseDate: Date
)
-private val module = SerializersModule {
- contextual(DateAsLongSerializer)
-}
-
-val format = Json { serializersModule = module }
-
fun main() {
val data = ProgrammingLanguage("Kotlin", SimpleDateFormat("yyyy-MM-ddX").parse("2016-02-15+00"))
- println(format.encodeToString(data))
+ println(Json.encodeToString(data))
}
diff --git a/guide/example/example-serializer-21.kt b/guide/example/example-serializer-21.kt
index f588a737..9a24b0aa 100644
--- a/guide/example/example-serializer-21.kt
+++ b/guide/example/example-serializer-21.kt
@@ -6,13 +6,30 @@ import kotlinx.serialization.json.*
import kotlinx.serialization.encoding.*
import kotlinx.serialization.descriptors.*
-// NOT @Serializable
-class Project(val name: String, val language: String)
-
-@Serializer(forClass = Project::class)
-object ProjectSerializer
+import kotlinx.serialization.modules.*
+import java.util.Date
+import java.text.SimpleDateFormat
+
+object DateAsLongSerializer : KSerializer<Date> {
+ override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("Date", PrimitiveKind.LONG)
+ override fun serialize(encoder: Encoder, value: Date) = encoder.encodeLong(value.time)
+ override fun deserialize(decoder: Decoder): Date = Date(decoder.decodeLong())
+}
+
+@Serializable
+class ProgrammingLanguage(
+ val name: String,
+ @Contextual
+ val stableReleaseDate: Date
+)
+
+private val module = SerializersModule {
+ contextual(DateAsLongSerializer)
+}
+
+val format = Json { serializersModule = module }
fun main() {
- val data = Project("kotlinx.serialization", "Kotlin")
- println(Json.encodeToString(ProjectSerializer, data))
+ val data = ProgrammingLanguage("Kotlin", SimpleDateFormat("yyyy-MM-ddX").parse("2016-02-15+00"))
+ println(format.encodeToString(data))
}
diff --git a/guide/example/example-serializer-22.kt b/guide/example/example-serializer-22.kt
index 7f098fa7..4eba74b0 100644
--- a/guide/example/example-serializer-22.kt
+++ b/guide/example/example-serializer-22.kt
@@ -6,23 +6,13 @@ import kotlinx.serialization.json.*
import kotlinx.serialization.encoding.*
import kotlinx.serialization.descriptors.*
-// NOT @Serializable, will use external serializer
-class Project(
- // val in a primary constructor -- serialized
- val name: String
-) {
- var stars: Int = 0 // property with getter & setter -- serialized
-
- val path: String // getter only -- not serialized
- get() = "kotlin/$name"
-
- private var locked: Boolean = false // private, not accessible -- not serialized
-}
-
+// NOT @Serializable
+class Project(val name: String, val language: String)
+
@Serializer(forClass = Project::class)
object ProjectSerializer
fun main() {
- val data = Project("kotlinx.serialization").apply { stars = 9000 }
- println(Json.encodeToString(ProjectSerializer, data))
+ val data = Project("kotlinx.serialization", "Kotlin")
+ println(Json.encodeToString(ProjectSerializer, data))
}
diff --git a/guide/example/example-serializer-23.kt b/guide/example/example-serializer-23.kt
new file mode 100644
index 00000000..4b7de25a
--- /dev/null
+++ b/guide/example/example-serializer-23.kt
@@ -0,0 +1,28 @@
+// This file was automatically generated from serializers.md by Knit tool. Do not edit.
+package example.exampleSerializer23
+
+import kotlinx.serialization.*
+import kotlinx.serialization.json.*
+import kotlinx.serialization.encoding.*
+import kotlinx.serialization.descriptors.*
+
+// NOT @Serializable, will use external serializer
+class Project(
+ // val in a primary constructor -- serialized
+ val name: String
+) {
+ var stars: Int = 0 // property with getter & setter -- serialized
+
+ val path: String // getter only -- not serialized
+ get() = "kotlin/$name"
+
+ private var locked: Boolean = false // private, not accessible -- not serialized
+}
+
+@Serializer(forClass = Project::class)
+object ProjectSerializer
+
+fun main() {
+ val data = Project("kotlinx.serialization").apply { stars = 9000 }
+ println(Json.encodeToString(ProjectSerializer, data))
+}
diff --git a/guide/test/SerializersTest.kt b/guide/test/SerializersTest.kt
index c151a150..bda3f7f4 100644
--- a/guide/test/SerializersTest.kt
+++ b/guide/test/SerializersTest.kt
@@ -113,50 +113,57 @@ class SerializersTest {
@Test
fun testExampleSerializer16() {
captureOutput("ExampleSerializer16") { example.exampleSerializer16.main() }.verifyOutputLines(
- "{\"name\":\"Kotlin\",\"stableReleaseDate\":1455494400000}"
+ "{\"name\":\"Kotlin\",\"releaseDates\":[1688601600000,1682380800000,1672185600000]}"
)
}
@Test
fun testExampleSerializer17() {
captureOutput("ExampleSerializer17") { example.exampleSerializer17.main() }.verifyOutputLines(
- "{\"stableReleaseDate\":\"2016-02-15\",\"lastReleaseTimestamp\":1657152000000}"
+ "{\"name\":\"Kotlin\",\"stableReleaseDate\":1455494400000}"
)
}
@Test
fun testExampleSerializer18() {
captureOutput("ExampleSerializer18") { example.exampleSerializer18.main() }.verifyOutputLines(
- "{\"name\":\"kotlinx.serialization\"}",
- "Box(contents=Project(name=kotlinx.serialization))"
+ "{\"stableReleaseDate\":\"2016-02-15\",\"lastReleaseTimestamp\":1657152000000}"
)
}
@Test
fun testExampleSerializer19() {
- captureOutput("ExampleSerializer19") { example.exampleSerializer19.main() }.verifyOutputLinesStart(
- "Exception in thread \"main\" kotlinx.serialization.SerializationException: Serializer for class 'Date' is not found.",
- "Please ensure that class is marked as '@Serializable' and that the serialization compiler plugin is applied."
+ captureOutput("ExampleSerializer19") { example.exampleSerializer19.main() }.verifyOutputLines(
+ "{\"name\":\"kotlinx.serialization\"}",
+ "Box(contents=Project(name=kotlinx.serialization))"
)
}
@Test
fun testExampleSerializer20() {
- captureOutput("ExampleSerializer20") { example.exampleSerializer20.main() }.verifyOutputLines(
- "{\"name\":\"Kotlin\",\"stableReleaseDate\":1455494400000}"
+ captureOutput("ExampleSerializer20") { example.exampleSerializer20.main() }.verifyOutputLinesStart(
+ "Exception in thread \"main\" kotlinx.serialization.SerializationException: Serializer for class 'Date' is not found.",
+ "Please ensure that class is marked as '@Serializable' and that the serialization compiler plugin is applied."
)
}
@Test
fun testExampleSerializer21() {
captureOutput("ExampleSerializer21") { example.exampleSerializer21.main() }.verifyOutputLines(
- "{\"name\":\"kotlinx.serialization\",\"language\":\"Kotlin\"}"
+ "{\"name\":\"Kotlin\",\"stableReleaseDate\":1455494400000}"
)
}
@Test
fun testExampleSerializer22() {
captureOutput("ExampleSerializer22") { example.exampleSerializer22.main() }.verifyOutputLines(
+ "{\"name\":\"kotlinx.serialization\",\"language\":\"Kotlin\"}"
+ )
+ }
+
+ @Test
+ fun testExampleSerializer23() {
+ captureOutput("ExampleSerializer23") { example.exampleSerializer23.main() }.verifyOutputLines(
"{\"name\":\"kotlinx.serialization\",\"stars\":9000}"
)
}