0
votes

I am using jackson for json deserializing in Scala.

I am trying to deserialize a json field which could either be a string or an object of a class that I have defined. For example:

{
    fieldName: "something"
    /*** OR ****/
    fieldName: Object of case class Sample(..........)
}

How do I deal with such a case and let Json automatically deserialize into a string or an object of the case class above depending on the input value.

1
The easiest way to use Jackson in Scala, is probably to use json4s or maybe rapture-json. - Peter Neyens

1 Answers

1
votes

One of the ways around is:

case class A(fieldName:String)
case class B(fieldName:Sample)  //your Sample is param 

 val tryResult = Try {
    JsonMethods.parse(json).extract[A]
  }.recover { case _ => JsonMethods.parse(json).extract[B] }

  println(tryResult.get) // can throw exception