如何在IntelliJ/Kotlin中设置序列化? [英] How to setup serialization in IntelliJ/Kotlin?

查看:813
本文介绍了如何在IntelliJ/Kotlin中设置序列化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为一个菜鸟问题道歉:我正在尝试检查序列化在Kotlin中的工作方式.

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

为此,我创建了一个像这样的Gradle项目:

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

仅添加一行即可编辑生成的build.gradle.kts

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"
    }
}

并创建此Kotlin源文件:

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'

我在这里做错了什么? (此外,我是否需要Gradle在IntelliJ/Kotlin 1.3.71中使用序列化?)

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

推荐答案

最后,弄清楚了. IntelliJ IDEA中的一个 BUG 阻碍了我的故障排除.

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

将答案留给可能通过Google找到此问题的人:

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

build.gradle.kt必须是

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")
}

官方说明中有一个错误的版本:否org.jetbrains.kotlin.config.

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

但是,这还不够.我正在从Kotlin文件执行运行".这会导致另一个错误

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

由于一个令人讨厌的错误(例如,我浪费了 HOURS HOURS 试图找出我做错了什么)

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

需要明确地执行构建项目".

这篇关于如何在IntelliJ/Kotlin中设置序列化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆