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

时间:2018-10-16 08:36:56

标签: scala objectmapper

我有包含内容的json文件:

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

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

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
  }

print语句的输出是:

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

Json文件包含“步骤”,但是在输出中,它没有与成员类RuleStep映射。

Rule类的scala类定义如下:

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

RuleStep类的scala类定义如下:

class RuleStep {
  var stepIdentifer: String = null
}

我不明白我错过了什么?我该怎么做才能将成员类(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"

1 个答案:

答案 0 :(得分:1)

Gson可能不适用于Scala类。有一个similar problem。但是mapper.writeValueAsString(rule)可以很好地工作并返回:

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

您还可以使用其他更方便使用的JSON库,例如spray-json甚至是基于功能范式的circe