I am using lift-json 2.6 and Scala 2.11.
I want to deserialise a JSON string representing a Map of 'sensors' to case classes (I don't care about serialisation back to JSON at all):
case class TemperatureSensor(
name: String, sensorType: String, state: TemperatureState)
case class TemperatureState(
on: Boolean, temperature: Float)
case class LightSensor(
name: String, sensorType: String, state: LightState)
case class LightState(
on: Boolean, daylight: Boolean)
What I have here are some common fields in each sensor class, with a type-dependant state
field, discriminated by the sensorType
property
The idea is I invoke a web service and get a map of sensor information back, this can be any number of any type of different sensors. I know the set of possible types in advance, but I do not know in advance which particular sensors will be returned.
The JSON looks like this:
{
"1":
{
name: "Temp1",
sensorType: "Temperature",
state:
{
on: true,
temperature: 19.4
}
},
"2":
{
name: "Day",
sensorType: "Daylight",
state:
{
on: true,
daylight: false
}
}
}
(The real data has many more fields, the above case classes and JSON is a cut-down version.)
To consume the JSON I start with:
val map = parse(jsonString).extract[Map[String,Sensor]]
This works when I omit the state
fields of course.
How can the extraction process be told which type of state
to choose at run-time, based on the value of the sensorType
field? Or do I have to write a custom deserialiser?
This question relates specifically to lift-json, not any other JSON library.