I'm trying to represent the following JSON as a Scala case class:
{
"cars": {
"THIS IS A DYNAMIC KEY 1": {
"name": "bla 1",
},
"THIS IS A DYNAMIC KEY 2": {
"name": "bla 2",
}
...
}
However, my JSON has dynamic keys that I won't know at runtime, and I'd like to use circe to encode/decode. I'm using the correct way to represent this using Scala?
import io.circe.generic.JsonCodec
@JsonCodec
case class Cars(cars: List[Car])
@JsonCodec
case class Car(whatShouldThisBe: CarDetails) // Not sure how to represent this?
@JsonCodec
case class CarDetails(name: String)
I think you can just use a Map[String, CarDetails]
. Your ADT then becomes:
import io.circe.generic.JsonCodec
@JsonCodec
case class Cars(cars: Map[String, CarDetails])
@JsonCodec
case class CarDetails(name: String)
The only tricky bit might be if you require there to be at least one CarDetails object, or if zero is acceptable. Circe does appear to support cats.data.NonEmptyMap
should that be required.