我想在Scala中用jackson反序列化json
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import com.fasterxml.jackson.module.scala.experimental.ScalaObjectMapper
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonCreator;
case class Metadata(@JsonProperty("hive_type_string") hive_type_string: String)
case class Field(@JsonProperty("name") name: String, @JsonProperty("type") typeField: String, @JsonProperty("nullable") nullable: Boolean, @JsonProperty("metadata") metadata: Metadata)
case class StructTable(@JsonProperty("type") typeField: String, @JsonProperty("fields") fields: Seq[Field])
val mapper = new ObjectMapper() with ScalaObjectMapper
mapper.registerModule(DefaultScalaModule)
val struct = mapper.readValue[StructTable](json_struct)
json_struct :
{ "类型":"结构", “领域”:[ { "name":"code_role", "类型":"字符串", “可为空”:真, “元数据”:{ "HIVE_TYPE_STRING":"字符串" } }, { "name":"libelle_role", "类型":"字符串", “可为空”:真, “元数据”:{ "HIVE_TYPE_STRING":"字符串" } } ] }
这是错误:com.fasterxml.jackson.databind.exc.InvalidDefinitionException:无法构造StructTable
的实例:像这样的非静态内部类只能通过使用默认的无参数实例化构造函数
有人可以帮我吗?
谢谢。
答案 0 :(得分:1)
如果您可以选择另一个库,例如 jsoniter-scala,请添加到您的依赖项中:
libraryDependencies ++= Seq(
// Use the %%% operator instead of %% for Scala.js
"com.github.plokhotnyuk.jsoniter-scala" %% "jsoniter-scala-core" % "2.6.2",
// Use the "provided" scope instead when the "compile-internal" scope is not supported in your build tool
"com.github.plokhotnyuk.jsoniter-scala" %% "jsoniter-scala-macros" % "2.6.2" % "compile-internal"
)
以下是解析输入并打印解析数据的代码片段:
import com.github.plokhotnyuk.jsoniter_scala.macros._
import com.github.plokhotnyuk.jsoniter_scala.core._
case class Metadata(@named("HIVE_TYPE_STRING") hive_type_string: String)
case class Field(name: String, @named("type") typeField: String, nullable: Boolean, metadata: Metadata)
case class StructTable(@named("type") typeField: String, fields: Seq[Field])
implicit val codec: JsonValueCodec[StructTable] = JsonCodecMaker.make
val json_struct = """{ "type":"struct", "fields":[ { "name":"code_role", "type":"string", "nullable":true, "metadata":{ "HIVE_TYPE_STRING":"string" } }, { "name":"libelle_role", "type":"string", "nullable":true, "metadata":{ "HIVE_TYPE_STRING":"string" } } ] }""";
val struct = readFromString(json_struct)
println(struct)
预期输出为:
StructTable(struct,List(Field(code_role,string,true,Metadata(string)), Field(libelle_role,string,true,Metadata(string))))
您也可以使用 Scastie here 在线运行它。