scalajson4s

json to scala case class


I am trying to read the below json into scala case class. I am able to bind the case class to json using json4s.

The problem is the expectedTypes would change for every table. It could be more or less number of elements and the name would be different. How to create a case class for this requirement?

{
  "filepattern": "product*.gzip",
  "replaceheader": "productid,name,market",
  "dataType": [
    {
      "expectedTypes": {
        "productId": "DOUBLE",
        "name": "STRING"
      }
    }
  ]
}

case class ExpectedTypes(
  productid: String,
  name: String
)
case class DataType(
  expectedTypes: ExpectedTypes
)
case class table(
  filepattern: String,
  replaceheader: Option[String],
  dataType: List[DataType]
)


Solution

  • If it's not predictable how many fields are you going to have in expectedTypes, you can use Map:

    case class Root(
    filepattern: String,
    replaceheader: Option[String],
    dataType: List[DataType]
    )
    
    case class DataType(
      expectedTypes: Map[String, String]
    )