Scala:ObjectMapper 无法将 JSON 映射到成员 class

Scala: ObjectMapper not able to map JSON to member class

我有 json 个文件,内容为:

{
  "ruleName": "rule1",
  "steps": [{
    "stepIdentifer": "SI1"
  }, {
    "stepIdentifer": "SI2"
  }]
}

我正在尝试使用以下代码将其映射到 scala class(规则):

import java.io.FileInputStream
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import com.fasterxml.jackson.databind.{DeserializationFeature, ObjectMapper}
import com.fasterxml.jackson.module.scala.experimental.ScalaObjectMapper
import com.google.gson.GsonBuilder

def main(args: Array[String]): Unit = {
    val file:String = "<file_path>";    
    val stream = new FileInputStream(file)
    val mapper = new ObjectMapper with ScalaObjectMapper
    mapper.registerModule(DefaultScalaModule)
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
    val rule: Rule = mapper.readValue[Rule](stream)    
    val gson = new GsonBuilder().setPrettyPrinting().create()
    println(gson.toJson(rule)) // PRINT_STATEMENT
  }

打印语句的输出是:

{
  "ruleName": "rule1",
  "steps": {}
}

Json 文件包含 "steps",但在输出中,它未与成员 class RuleStep 映射。

Scala Class规则class的定义如下:

class Rule {
  var ruleName: String = null;
  var steps:List[RuleStep] = null;
}

Scala Class RuleStep class 的定义如下:

class RuleStep {
  var stepIdentifer: String = null
}

我不明白我错过了什么?我应该怎么做才能将成员 class (RuleStep) 与嵌套 Json(属性键:"steps")相匹配?

版本:

Scala = 2.11
libraryDependencies += "com.google.code.gson" % "gson" % "2.6.2"
libraryDependencies += "com.fasterxml.jackson.core" % "jackson-databind" % "2.6.2"
libraryDependencies += "com.fasterxml.jackson.core" % "jackson-core" % "2.6.2"

可能 Gson 不能与 Scala 类 正常工作。有一个similar problem。但是 mapper.writeValueAsString(rule) 效果很好并且 returns:

{"ruleName":"rule1","steps":[{"stepIdentifer":"SI1"},{"stepIdentifer":"SI2"}]}

您还可以使用其他 JSON 更方便使用的库,例如 spray-json or even circe 基于函数式范例的