Comments (21)
this one working:
val map = mapOf(1 to "1", 2 to "2")
val serial = (IntSerializer to StringSerializer).map
val s = JSON.unquoted.stringify(serial, map)
assertEquals("{1:1,2:2}",s)
but not this:
val map23 = mapOf(1 to mapOf(3 to "4"), 2 to mapOf(4 to "5"))
val serial = (IntSerializer to StringSerializer).map
val s = JSON.stringify(serial, map23)
is it possible to serialize nested maps?
from kotlinx.serialization.
For root-level collections you must specify serializers explicitly: #27
from kotlinx.serialization.
I see, maybe this should be stated in the documentation somewhere?
from kotlinx.serialization.
@sandwwraith Just for reference can you provide an example?
In particular I'm trying to work with a map and I'm not sure from which Pair to get the map property. So far I couldn't find any example to illustrate this use case.
from kotlinx.serialization.
@flaghacker it was recently added: 9f19871#diff-04c6e90faac2675aa89e2176d2eec7d8R75
from kotlinx.serialization.
@jivimberg You should use .map
function on Pair<KeySerializer, ValueSerializer>
. For @Serializable
marked types serializer is companion object, and for built-ins you can use IntSerializer
, etc from internal
package
from kotlinx.serialization.
Hmm I still don't really get what I'm supposed to do. An edaptation of @elizarov's (proposed) example in #27 doesn't compile:
val list = JSON.parse("""{"foo": "Hello World!"""", Foo.list)
And I'm looking to go the other way around, serializing an object.
from kotlinx.serialization.
seems like arguments just messed up: KSerializer
goes first argument in function, so you need JSON.stringify(Foo.list, """[{"foo": "bar"}]""")
You can find more examples in tests: https://github.com/Kotlin/kotlinx.serialization/blob/master/runtime/common/src/test/kotlin/kotlinx/serialization/CustomSerializersTest.kt#L88
from kotlinx.serialization.
Hmm, with that exact code the gradle build fails with:
Type inference failed: Cannot infer type parameter T in fun <T> stringify(saver: KSerialSaver<T>, obj: T): String
None of the following substitutions
(KSerialSaver<String>,String)
(KSerialSaver<List<Foo>>,List<Foo>)
can be applied to
(KSerializer<List<Foo>>,String)
Also Foo.list
is an unresolved reference according to Idea, is that normal?
from kotlinx.serialization.
Sorry, of course .stringify
should have List<Foo>
as second argument - it's serializing; and .parse
should have string as second argument to get back List<Foo>
Yes, that's normal because regular Kotlin plugin don't know about synthetic objects. We will release small additional plugin soon.
from kotlinx.serialization.
Hmm the signature of .stringify
: fun <T> stringify(saver: KSerialSaver<T>, obj: T): String
, so it looks like Foo.list
has to go in the first place after all? Maybe I had to specify the type argument explicitly?
I can't reproduce my issue from yesterday anymore, now gradle build
also complains: "Unresolved reference: list", still your exact code. My build.gradle
: (should be the same as yesterday really)
buildscript {
ext.kotlin_version = "1.1.51"
ext.kotlinx_html_version = "0.6.4"
ext.kotlinx_serialization_version = "0.2"
ext.kotlin_src = "src/"
ext.web_dir = "web"
ext.build_dir = "build/kotlin/main"
repositories {
mavenCentral()
jcenter()
maven { url "https://plugins.gradle.org/m2/" }
maven { url "https://kotlin.bintray.com/kotlinx" }
}
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath "org.jetbrains.kotlinx:kotlinx-gradle-serialization-plugin:$kotlinx_serialization_version"
}
}
apply plugin: "kotlin2js"
apply plugin: "kotlin-dce-js"
apply plugin: "kotlinx-serialization"
repositories {
mavenCentral()
jcenter()
maven { url "http://dl.bintray.com/kotlin/kotlin-eap-1.1" }
maven { url "https://kotlin.bintray.com/kotlinx" }
}
dependencies {
compile "org.jetbrains.kotlin:kotlin-stdlib-js:$kotlin_version"
compile "org.jetbrains.kotlinx:kotlinx-html-js:$kotlinx_html_version"
compile "org.jetbrains.kotlinx:kotlinx-serialization-runtime-js:$kotlinx_serialization_version"
}
sourceSets {
main.kotlin.srcDirs = [kotlin_src]
}
compileKotlin2Js {
kotlinOptions.moduleKind = "plain"
kotlinOptions.outputFile = "${build_dir}/main.js"
kotlinOptions.sourceMap = true
kotlinOptions.sourceMapEmbedSources = "always"
}
task copyJsBuildFiles(type: Copy) {
dependsOn runDceKotlinJs
from "${build_dir}/min"
into web_dir
}
task web {
dependsOn copyJsBuildFiles
}
I'm sorry for the messy situation.
from kotlinx.serialization.
You build file looks OK, can you provide some example code?
from kotlinx.serialization.
import kotlinx.serialization.json.JSON
fun main(args: Array<String>) {
val list = listOf(Foo("a"), Foo("b"))
println(JSON.stringify(Foo.list, """[{"foo": "bar"}]"""))
}
@Serializable
data class Foo(val foo: String?)
Is my full code right now.
from kotlinx.serialization.
You've just mixed up JSON methods:
val list = listOf(Foo("a"), Foo("b"))
println(JSON.stringify(Foo.list, list))
will print serialized list, and
println(JSON.parse(Foo.list, """[{"foo": "bar"}]"""))
will print deserialized list
from kotlinx.serialization.
Yes, @coolemza , it's possible, but you need to specify a nested serializer too:
val serial = (IntSerializer to (IntSerializer to StringSerializer).map).map
I suggest you to wrap this structure in a @Serializable
class to let the compiler plugin build serializer for you
from kotlinx.serialization.
Do you have an example of how to get it right with Map? I have been desperately trying all possible combinations with or without generics, can't get it working:
JSON.parse(Pair.map, message)
JSON.parse(Pair<String, Int>.map, message)
JSON.parse<Map<String, Int>>(Pair.map, message)
...
from kotlinx.serialization.
@pmiklos you need to call .map
extension function on instance of Pair<KSerializer<K>, KSerializer<V>>
to get KSerializer<Map<K,V>>
. So serializer for your example would be Pair(StringSerializer, IntSerializer).map
. IntSerializer
and etc located in the kotlinx.serialization.internal
package
from kotlinx.serialization.
Thanks, that works indeed. I just realized that StringSerializer and IntSerializer are objects and not classes...
from kotlinx.serialization.
Most of use-cases described here are now mentioned in documentation.
Feel free to open new issues if you have some problems.
from kotlinx.serialization.
is it possible to serialize nested maps of dynamic unknown depth?
from kotlinx.serialization.
@IARI There is nothing in the architecture that prevents the dynamic unknown depth. If it works for depth 2 it works for depth 10 it works for depth 50. (There are practical limits due to JVM stack size)
from kotlinx.serialization.
Related Issues (20)
- Cannot serializer flow of Objects HOT 4
- kotlinx.serialization.SerializationException: Enum class Country does not contain element with name 'MISSING' at path $[2] HOT 1
- [Possible duplicate] Small inconsistency in the logic of encoding of fields with defaults HOT 1
- Didn't find class "kotlinx.serialization.json.Json" on path: DexPathList HOT 1
- typealiased @Serializable cannot be used as type hints HOT 1
- Value classes not using encodeInlineElement and inefficient boxing of primitive values
- Errors revealed only on run-time HOT 1
- ERROR: org.jetbrains.kotlinx.serialization.compiler.extensions.SerializationResolveExtension caused LinkageError HOT 3
- Allow annotation meta-annotations with Serializable
- Streaming performance: kotlinx-io & Okio integrations
- kotlinx.serialization.json deserialize error HOT 1
- Quoted booleans are being allowed even with `isLenient = false` HOT 6
- very strange serialization HOT 2
- The built-in String type (JsonPrimitive/JsonLiteral) puts double quotes around the string value HOT 8
- Don't check kind if needn't type discriminator for enum and primitive HOT 5
- 2.0.20 with generatedSerializer and reference to interface: SealedClassSerializer init: subclassSerializers contains null HOT 2
- [protobuf] How to encode/decode map with null value?
- Option to serialize enums as lowercase/snake_case HOT 4
- hande single quotes when `isLenient=true` HOT 3
- Support for `serializer<@Contextual T>` HOT 3
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from kotlinx.serialization.