Giter Club home page Giter Club logo

Comments (21)

coolemza avatar coolemza commented on August 25, 2024 1

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.

sandwwraith avatar sandwwraith commented on August 25, 2024

For root-level collections you must specify serializers explicitly: #27

from kotlinx.serialization.

KarelPeeters avatar KarelPeeters commented on August 25, 2024

I see, maybe this should be stated in the documentation somewhere?

from kotlinx.serialization.

jivimberg avatar jivimberg commented on August 25, 2024

@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.

sandwwraith avatar sandwwraith commented on August 25, 2024

@flaghacker it was recently added: 9f19871#diff-04c6e90faac2675aa89e2176d2eec7d8R75

from kotlinx.serialization.

sandwwraith avatar sandwwraith commented on August 25, 2024

@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.

KarelPeeters avatar KarelPeeters commented on August 25, 2024

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.

sandwwraith avatar sandwwraith commented on August 25, 2024

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.

KarelPeeters avatar KarelPeeters commented on August 25, 2024

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.

sandwwraith avatar sandwwraith commented on August 25, 2024

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.

KarelPeeters avatar KarelPeeters commented on August 25, 2024

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.

sandwwraith avatar sandwwraith commented on August 25, 2024

You build file looks OK, can you provide some example code?

from kotlinx.serialization.

KarelPeeters avatar KarelPeeters commented on August 25, 2024
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.

sandwwraith avatar sandwwraith commented on August 25, 2024

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.

sandwwraith avatar sandwwraith commented on August 25, 2024

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.

pmiklos avatar pmiklos commented on August 25, 2024

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.

sandwwraith avatar sandwwraith commented on August 25, 2024

@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.

pmiklos avatar pmiklos commented on August 25, 2024

Thanks, that works indeed. I just realized that StringSerializer and IntSerializer are objects and not classes...

from kotlinx.serialization.

sandwwraith avatar sandwwraith commented on August 25, 2024

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.

IARI avatar IARI commented on August 25, 2024

is it possible to serialize nested maps of dynamic unknown depth?

from kotlinx.serialization.

pdvrieze avatar pdvrieze commented on August 25, 2024

@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)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo 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.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.