How to setup serialization in IntelliJ/Kotlin?

一世执手 提交于 2020-04-07 08:12:08

问题


My apologies for a noob question: I'm trying to check out how serialization works in Kotlin.

To this end, I created a Gradle project like this:

edited the generated build.gradle.ktsby adding just one line

plugins {
    java
    kotlin("jvm") version "1.3.71"
    id("org.jetbrains.kotlin.plugin.serialization") version "1.3.71"
}

group = "org.example"
version = "1.0-SNAPSHOT"

repositories {
    mavenCentral()
}

dependencies {
    implementation(kotlin("stdlib-jdk8"))
    testCompile("junit", "junit", "4.12")
}

configure<JavaPluginConvention> {
    sourceCompatibility = JavaVersion.VERSION_1_8
}
tasks {
    compileKotlin {
        kotlinOptions.jvmTarget = "1.8"
    }
    compileTestKotlin {
        kotlinOptions.jvmTarget = "1.8"
    }
}

and created this Kotlin source file:

import kotlinx.serialization.*
import kotlinx.serialization.json.*

@Serializable
data class Data(val a: Int, val b: String = "42")

But when I build this project, I get this error:

Unresolved reference: kotlinx

If I remove the first two offending lines, I get this error instead:

Cannot access 'Serializable': it is internal in 'kotlin.io'

What am I doing wrong here? (Also, do I need Gradle to use serialization in IntelliJ/Kotlin 1.3.71? )


回答1:


I think you need to change the build gradle:

Have a look a this example gradle file in Kotlin DSL:

plugins {
    kotlin("jvm") version "1.3.71"
    kotlin("plugin.serialization") version "1.3.71"
}

dependencies {
    val kotlinVersion = "1.3.70"
    classpath(kotlin("gradle-plugin", version = kotlinVersion))
    classpath(kotlin("serialization", version = kotlinVersion))
}

Source: https://proandroiddev.com/kotlinx-serialization-83815cc1c57b




回答2:


Finally, figured it out. A BUG in IntelliJ IDEA was foiling my troubleshooting.

Leaving the answer for anyone who might find this question via Google:

build.gradle.kt needs to be

plugins {
    java
    kotlin("jvm") version "1.3.71"
    kotlin("plugin.serialization") version "1.3.71"
}

repositories {
    // artifacts are published to JCenter
    jcenter()
}

dependencies {
    implementation(kotlin("stdlib", org.jetbrains.kotlin.config.KotlinCompilerVersion.VERSION))
    implementation("org.jetbrains.kotlinx:kotlinx-serialization-runtime:0.20.0")
}

The official instructions have a buggy version of this: no org.jetbrains.kotlin.config.

However, this is not enough. I was executing "Run" from the Kotlin file. This leads to another error

error: unable to evaluate script, no scripting plugin loaded

due to a nasty bug (as in, I wasted HOURS and HOURS trying to figure out what I was doing wrong) https://youtrack.jetbrains.com/issue/KT-37814

One needs to explicitly execute "Build project".



来源:https://stackoverflow.com/questions/60940476/how-to-setup-serialization-in-intellij-kotlin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!