我是 Scala 的新玩家,正在尝试使用 Gson
到 case class
字符串的 JSON
包。我有两个环境可以解决这个问题。两者都运行相同的代码。
代码是:
//package flink
import com.google.gson.Gson
object HelloWorld {
case class OutputMeasurements(
TotalYield : Double,
TotalYield_delta: Double,
is_init: Int,
is_reset: Int
)
case class OutputSchema(
site: String,
measurements: OutputMeasurements,
rec_time: String
)
def ToJsonString(dataClass: OutputSchema): String ={
val gson = new Gson
val jsonString = gson.toJson(dataClass)
return jsonString
}
def main(args: Array[String]): Unit = {
println("Hello, world!")
val x = OutputMeasurements(10, 20, 3, 4)
val y = OutputSchema("a", x, "bcd")
println(ToJsonString(y))
}
}
首先是本地的,使用IntelliJ IDEA
编译jar
和maven
,然后就成功了。
返回:
Hello, world!
{"site":"a","measurements":{"TotalYield":10.0,"TotalYield_delta":20.0,"is_init":3,"is_reset":4},"rec_time":"bcd"}
第二,使用本地编译的jar作为库(flink.jar
)复制到K8S pod中并在scala shell中运行以进行测试/POC。
Docker 镜像:flink:1.11.2-scala_2.11
运行 Shell:bin/start-scala-shell.sh remote localhost 8081 -a /opt/flink/flink.jar
Java 版本:
openjdk version "1.8.0_275"
OpenJDK Runtime Environment (build 1.8.0_275-b01)
OpenJDK 64-Bit Server VM (build 25.275-b01, mixed mode)
运行 CMD:
<copy and paste the code of object HelloWorld>
HelloWorld.main(Array("test"))
返回:
Hello, world!
java.lang.InternalError: Malformed class name
at java.lang.Class.getSimpleName(Class.java:1330)
at java.lang.Class.isAnonymousClass(Class.java:1411)
at com.google.gson.internal.Excluder.isAnonymousOrLocal(Excluder.java:226)
at com.google.gson.internal.Excluder.excludeClassChecks(Excluder.java:202)
at com.google.gson.internal.Excluder.create(Excluder.java:113)
at com.google.gson.Gson.getAdapter(Gson.java:458)
at com.google.gson.Gson.toJson(Gson.java:696)
at com.google.gson.Gson.toJson(Gson.java:683)
at com.google.gson.Gson.toJson(Gson.java:638)
at com.google.gson.Gson.toJson(Gson.java:618)
at HelloWorld$.ToJsonString(<console>:92)
at HelloWorld$.main(<console>:100)
... 30 elided
是scala shell的问题吗?如何在 Scala shell 中成功运行到 POC/测试?
谢谢
答案 0 :(得分:0)
你能把 case 类 OutputMeasurements
和 OutputSchema
放在对象 HelloWorld
之外吗?