将困难的json转换为对象(scala,jackson)

时间:2019-01-20 20:26:22

标签: json scala jackson mapping

我正在尝试将json转换为scala对象,但字段未初始化。

object MyJson {
  val myJson =
    """{
          "addresses":{
             "address":[
                {
                   "addressLine1":{
                      "com.jacksontest.AddressLine":{
                         "value":null,
                         "transliteratedValue":null,
                         "naCode":null
                      }
                   },
                   "addressLine2":{
                      "com.jacksontest.AddressLine":{
                         "value":{
                            "string":"MY ADDRESS"
                         },
                         "transliteratedValue":null,
                         "naCode":null
                      }
                   }
                }
             ]
          }
       }"""
}


case class Organization(addresses: Addresses)
case class AddressLine(value: StringWrapper,
                       transliteratedValue: String,
                       naCode: String)
case class Address(addressLine1: AddressLine,
                   addressLine2: AddressLine)
case class Addresses(address: List[Address])
case class StringWrapper(string: String)


object Main {
  val mapper = new ObjectMapper() with ScalaObjectMapper
  mapper.registerModule(DefaultScalaModule)
  mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)

  def main(args: Array[String]): Unit = {
    val parsedJson = mapper.readValue(MyJson.myJson, classOf[Organization])
    println(parsedJson)
  }
}

我的结果:

Organization(Addresses(Listes(List(Address(Address(AddressLine(null,null,null),AddressLine(null,null,null))))))

我在做什么错了?

1 个答案:

答案 0 :(得分:3)

我认为您缺少com.jacksontest.AddressLine的映射

case class Organization(addresses: Addresses)
case class AddressLine(value: StringWrapper,
                       transliteratedValue: String,
                       naCode: String)
case class JacksonAddressLine(`com.jacksontest.AddressLine` : AddressLine)
case class Address(addressLine1: JacksonAddressLine,
                   addressLine2: JacksonAddressLine)
case class Addresses(address: List[Address])
case class StringWrapper(string: String)