简体   繁体   English

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

[英]Scala: ObjectMapper not able to map JSON to member class

I have json file with content: 我有内容的json文件:

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

I am trying to map it to scala class (Rule) using following code: 我正在尝试使用以下代码将其映射到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
  }

Output from print statement is: 打印语句的输出为:

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

Json file contains "steps", but in output, it is not mapped with member class RuleStep. Json文件包含“步骤”,但是在输出中,它没有与成员类RuleStep映射。

Scala Class definition of Rule class is as follow: 规则类的Scala类定义如下:

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

Scala Class definition of RuleStep class is as follow: RuleStep类的Scala类定义如下:

class RuleStep {
  var stepIdentifer: String = null
}

I am not able to understand what I missed? 我无法理解我错过了什么? What should I do to match member class (RuleStep) with nested Json (attribute key: "steps")? 我该怎么做才能将成员类(RuleStep)与嵌套的Json(属性键:“ steps”)匹配?

Versions: 版本:

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"

Probably Gson doesn't work with Scala classes properly. Gson可能无法正确处理Scala类。 There was a similar problem . 出现了类似的问题 But mapper.writeValueAsString(rule) works well and returns: 但是mapper.writeValueAsString(rule)可以正常工作并返回:

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

Also you can use other JSON libraries which are more convenient to use like spray-json or even circe which is based on functional paradigm 您还可以使用其他更方便使用的JSON库,例如spray-json甚至基于函数范式的circe

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM