How to deserialize a JSON object of type and value to map in Scala?

532 Views Asked by At

I need to deserialize some JSON that looks like the following:

{ "states": 
  { "Position" : { "x": 1, "y": 2, "z": 3 },  
    "Timestamp" : { "value" : 123 } }
}

The fields named Position and Timestamp are the name of the class to be serialized.

The only way I have been able to deserialize this at the moment is to transform this JSON this into a format that lift web JSON understands. For example:

{ "states": [
    { "jsonClass": "Position", "x": 1, "y": 2, "z": 3 },  
    { "jsonClass": "Timestamp", "value" : 123 } 
   ]}

With formats as follows

implicit val formats = new DefaultFormats {
  override val typeHintFieldName = "type"
  override val typeHints = ShortTypeHints(List(classOf[Position], classOf[Timestamp]))
}

Is it possible to deserialize the top form?

1

There are 1 best solutions below

1
On

Using Jackson, then:

case class Position(x: Int, y: Int, z: Int)
case class Timestamp(value: Int)
case class State(position: Position, timestamp: Timestamp)
case class States(states: Seq[State])

object Test extends App {

  val mapper = new ObjectMapper with ScalaObjectMapper
  mapper.registerModule(DefaultScalaModule)
  mapper.configure(SerializationFeature.WRITE_SINGLE_ELEM_ARRAYS_UNWRAPPED, true)
  mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true)
  val states = mapper.readValue[Seq[States]]( """{
                                                |  "states": {
                                                |    "position" : { "x": 1, "y": 2, "z": 3 },
                                                |    "timestamp" : { "value" : 123 }
                                                |  }
                                                |}""".stripMargin)
  println(states)
}

Gives

List(States(List(State(Position(1,2,3),Timestamp(123)))))

Note1: The configure lines allow Jackson to treat an {} as a single element array, in cases where the Json uses badgerfish notation

Note2: If you have upper case field names, rename the field names in the case class to match, eg case class State(Position: Position, Timestamp: Timestamp)