7

寻找一个使用jackson和scala进行多态序列化反序列化的好例子

有一个例外:

线程“主”块引用 org.codehaus.jackson.map.exc.UnrecognizedPropertyException 中的异常:无法识别的字段“动物”(动物园类),未标记为可忽略

尝试以下代码后:

    import org.codehaus.jackson.annotate.{ JsonTypeInfo, JsonSubTypes }
    import org.codehaus.jackson.annotate.JsonSubTypes.Type

    @JsonTypeInfo(
      use = JsonTypeInfo.Id.NAME,
      include= JsonTypeInfo.As.PROPERTY,
      property = "type"
    )
    @JsonSubTypes(Array(
      new Type(value= classOf[Cat] , name = "cat"),
      new Type(value= classOf[Dog] , name = "dog")
    )
    )
    abstract class Animal {
      val name:String  = "NoName"

    }
class Cat extends Animal{
   val favoriteToy = "edi"
}
class Dog extends Animal{
  val breed = "German Shepherd"
  val color = "brown"
}
class Zoo {
  val animals = new scala.collection.mutable.ListBuffer[Animal]
}
import org.codehaus.jackson.map.ObjectMapper

object Foo {
  def main (args:Array[String]) {
    val mapper = new ObjectMapper()
     mapper.setPropertyNamingStrategy(CamelCaseNamingStrategy )
    val source = scala.io.Source.fromFile("input.json" )
    val input = source.mkString
    source.close
     val zoo = mapper.readValue(input,classOf[Zoo])
    println(mapper.writeValueAsString(zoo))
  }
import org.codehaus.jackson.map.introspect.{AnnotatedField, AnnotatedMethod}
import org.codehaus.jackson.map.{MapperConfig, PropertyNamingStrategy}

object CamelCaseNamingStrategy extends PropertyNamingStrategy{
 override def nameForGetterMethod (config: MapperConfig[_], method: AnnotatedMethod, defaultName: String) =
 {
   translate(defaultName)
 }

 override def nameForSetterMethod (config: MapperConfig[_], method: AnnotatedMethod, defaultName: String) = {
   translate(defaultName)
 }

  override def nameForField  (config: MapperConfig[_], field: AnnotatedField, defaultName: String) = {
    translate(defaultName)
  }

  def translate(defaultName:String) = {
    val nameChars = defaultName.toCharArray
    val nameTranslated = new StringBuilder(nameChars.length*2)
    for ( c <- nameChars){
      if (Character.isUpperCase(c)){
        nameTranslated.append("_")
      }
      nameTranslated.append( Character.toLowerCase(c))
    }
    nameTranslated.toString
  }

}

文件 input.json

{
"animals":
  [
    {"type":"dog","name":"Spike","breed":"mutt","color":"red"},
    {"type":"cat","name":"Fluffy","favoriteToy":"spider ring"}
  ]
}
4

2 回答 2

8

如果您在 Scala 中进行多态反序列化,我强烈建议您使用案例类和 Jackson 的 scala 模块。

object Test {
  import com.fasterxml.jackson.annotation.JsonSubTypes.Type
  import com.fasterxml.jackson.annotation.{JsonSubTypes, JsonTypeInfo}
  import com.fasterxml.jackson.databind.ObjectMapper
  import com.fasterxml.jackson.module.scala.DefaultScalaModule
  import com.fasterxml.jackson.module.scala.experimental.ScalaObjectMapper

  @JsonTypeInfo(
    use = JsonTypeInfo.Id.NAME,
    include = JsonTypeInfo.As.PROPERTY,
    property = "type"
  )
  @JsonSubTypes(Array(
    new Type(value = classOf[Cat], name = "cat"),
    new Type(value = classOf[Dog], name = "dog")
  ))
  trait Animal

  case class Dog(name: String, breed: String, leash_color: String) extends Animal
  case class Cat(name: String, favorite_toy: String) extends Animal
  case class Zoo(animals: Iterable[Animal])

  def main(args: Array[String]): Unit = {
    val objectMapper = new ObjectMapper with ScalaObjectMapper
    objectMapper.registerModule(DefaultScalaModule)

    val dogStr = """{"type": "dog", "name": "Spike", "breed": "mutt",  "leash_color": "red"}"""
    val catStr = """{"type": "cat", "name": "Fluffy", "favorite_toy": "spider ring"}"""
    val zooStr = s"""{"animals":[$dogStr, $catStr]}"""

    val zoo = objectMapper.readValue[Zoo](zooStr)

    println(zoo)
    // Prints: Zoo(List(Dog(Spike,mutt,red), Cat(Fluffy,spider ring)))
  }
}
于 2014-11-03T18:14:42.467 回答
5

好的,这里是一个工作示例,使用基于Deserialize JSON with Jackson into Polymorphic by Programmer Bruce的 scala :

import org.codehaus.jackson.annotate.JsonSubTypes.Type
import org.codehaus.jackson.annotate.{JsonSubTypes, JsonTypeInfo}

@JsonTypeInfo(
  use = JsonTypeInfo.Id.NAME,
  include= JsonTypeInfo.As.PROPERTY,
  property = "type"
)
@JsonSubTypes(Array(
  new Type(value= classOf[Cat] , name = "cat"),
  new Type(value= classOf[Dog] , name = "dog")
)
)
abstract class Animal {
  var name:String =""

}

class Dog extends Animal{
  var breed= "German Shepherd"
  var color = "brown"
}

class Cat extends Animal{
   var favoriteToy:String = "nothing"
}


class Zoo {
  var animals = new Array[Animal](5)
}


import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility
import org.codehaus.jackson.annotate.JsonMethod
import org.codehaus.jackson.map.{DeserializationConfig, ObjectMapper}

object Foo {
   def main (args:Array[String]) {
    val mapper = new ObjectMapper().setVisibility(JsonMethod.FIELD,Visibility.ANY)
     mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES,false)
    val source =  scala.io.Source.fromFile("/input.json" )
    val input = source.mkString
     println("input " + input)
    source.close
     val zoo = mapper.readValue(input,classOf[Zoo])

    println(mapper.writeValueAsString(zoo))
  }

}

文件:input.json {“动物”:[ {“类型”:“狗”,“名称”:“穗”,“品种”:“mutt”,“颜色”:“红色”},{“类型”: "cat","name":"Fluffy","favoriteToy":"蜘蛛环"} ] }

于 2013-06-17T08:15:12.767 回答