-2

We have two case classes which has different parameters. For Example -

case class OneType(@JsonProperty("column1") column1 : String,
                   @JsonProperty("column2") column2 : Map[String,Any],
                   @JsonProperty("column3") column3 : Seq[String]
                  )
case class AnotherType(@JsonProperty("column1") column1 : String,
                       @JsonProperty("column2") column2 : BigInt,
                       @JsonProperty("column3") column3 : Map[String,String] 
                      )

These two case classes will be used to de-serialize incoming JSON messages(by mapping them with the case class). They need to be used in another class declaration. For example -

class JSONDeserialize extends StreamManager(String, Either[Failed, OneType/AnotherType]){
}

How to dynamically assign appropriate case class(here either OneType or AnotherType) into JSONDeserialize class without having duplicate JSONDeserialize class?

Pralay Ghosh
  • 15
  • 1
  • 2
  • 10

1 Answers1

1

I am thinking of 2 ways you can do that.

1- You could Join both case classes in a single case class, like this:

       case class T(      
                   @JsonProperty("column1") column1 : Option[String],
                   @JsonProperty("column2") column2 : Option[Map[String,Any]],
                   @JsonProperty("column3") column3 : Option[Seq[String]],
                   @JsonProperty("column4") column4 : Option[String],
                   @JsonProperty("column5") column5 : Option[BigInt],
                   @JsonProperty("column6") column6 : Option[Map[String,String]] 
                  )

And you always read the only type T, that have optional fields, with Option, which means the data might not exist, can be None.

2- You could try to read OneType and if it fails read AnotherType.

Pedro Correia Luís
  • 1,085
  • 6
  • 16