Vineet Goel
Vineet Goel

Reputation: 2148

Scala Jackson Deserialize to String or Map

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.

Upvotes: 0

Views: 433

Answers (1)

ka4eli
ka4eli

Reputation: 5424

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

Upvotes: 1

Related Questions