Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looking for a good example of polymorphic serialization deserialization using jackson with scala

Tags:

jackson

scala

Looking for a good example of polymorphic serialization deserialization using jackson with scala

got an exception :

Exception in thread "main" Blockquote org.codehaus.jackson.map.exc.UnrecognizedPropertyException: Unrecognized field "animals" (Class Zoo), not marked as ignorable

after trying the following code :

    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
  }

}

file input.json

{
"animals":
  [
    {"type":"dog","name":"Spike","breed":"mutt","color":"red"},
    {"type":"cat","name":"Fluffy","favoriteToy":"spider ring"}
  ]
}
like image 203
igx Avatar asked Jun 16 '13 16:06

igx


1 Answers

If you're doing polymorphic deserialization in Scala I'd strongly recommend using case classes and Jackson's scala module.

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)))
  }
}
like image 55
Nate Avatar answered Nov 15 '22 00:11

Nate