打包 msi 后 Gson 无法工作 - 桌面撰写

问题描述 投票:0回答:1

我在 Desktop Compose 中处理一个小项目时遇到了一些麻烦。 我有以下 3 个功能:

package utilities

import com.google.gson.Gson
import serializables.Settings
import java.io.File

fun CheckSettingsFile () {
   if (!File("settings.json").exists()) {
       File("settings.json").createNewFile()
       with(File("settings.json")) {
           val settings = Settings("192.168.1.254","3344")
           val gson = Gson()
           gson.newBuilder().setPrettyPrinting()
           val toWrite = gson.toJson(settings)
           this.writeText(toWrite)
       }
   }
}

fun SaveSettings (s : Settings) {
    val gson = Gson()
    gson.newBuilder().setPrettyPrinting()
    val serialized = gson.toJson(s)
    try {
        with(File("settings.json")) {
            this.writeText(serialized)
        }
    } catch (err :Exception) {
        println(err.message)
    }
}

fun LoadSettings () : Settings {
    val gson = Gson()
    return  gson.fromJson(File("settings.json").readText(), Settings::class.java)
}

从 IntelliJIDEA 运行时,代码运行完美,但在打包为 Windows 的 msi 或 exe 后,我偶然发现了此错误:

 Unable to create instance of class serializables.Settings. Registering an InstanceCreator or a TypeAdapter for this type, or adding a no-args constructor may fix this problem.

我没有尝试像错误消息所示那样解决它,因为我想首先了解导致错误的原因。

这是 gradle.settings.kts


plugins {
    kotlin("jvm")
    id("org.jetbrains.compose")

}

group = "com.eticket"
version = "1.0-SNAPSHOT"

repositories {
    mavenCentral()
    maven("https://maven.pkg.jetbrains.space/public/p/compose/dev")
    google()
}

dependencies {
    implementation("com.google.code.gson:gson:2.10.1")
    implementation(compose.desktop.currentOs)

}

compose.desktop {
    application {
        mainClass = "MainKt"
        nativeDistributions {
            targetFormats(TargetFormat.Dmg, TargetFormat.Msi, TargetFormat.Deb, TargetFormat.Exe)
            packageName = "eTicket"
            packageVersion = "1.0.0"
            windows {
                shortcut = true
                iconFile.set(project.file("stamp-icon.ico"))
                console = false
                menu = true
            }
        }
    }
} ```

Thanks to everyone who feels to share a hint!
json kotlin serialization gson compose-desktop
1个回答
0
投票

很可能您的

Settings
类没有无参数构造函数,因此您当前隐式依赖于 Gson 用于创建此类实例的
sun.misc.Unsafe
,请参阅
GsonBuilder.disableJdkUnsafe()
了解更多详细信息。

sun.misc.Unsafe
是模块
jdk.unsupported
的一部分,因此您可以通过在 Gradle 设置中添加以下内容来解决此问题:

compose.desktop {
    application {
        ...
        nativeDistributions {
            ...
            modules("jdk.unsupported")
        }
    }
}

(基于此评论

但是,请注意,Gson 并不完全支持 Kotlin(例如,参见此问题),因此最好切换到具有明确 Kotlin 支持的库,例如 Moshi、Jackson 或 kotlinx-serialization。

© www.soinside.com 2019 - 2024. All rights reserved.