Search code examples
scalaakka-httpspray-json

Akka-HTTP JSON serialization


How does one control the deserialization for spray-json? For example, I have a class defined as:

case class A (Name:String, Value:String)

And I would like to deserialize the following JSON into a List of A objects:

{
   "one": "1",
   "two": "2"
}

and it should become:

List(A("one", "1"), A("two", "2"))

The problem is that the default JSON representation of that List is this one, which I do not want:

[
   { "Name": "one", "Value": "1" },
   { "Name": "two", "Value": "2" }
]

How can I accomplish this?


Solution

  • You can write your own custom deserializer for the structure you are looking for:

      case class A(Name:String, Value:String)
    
      implicit object ListAFormat extends RootJsonReader[List[A]] {
        override def read(json: JsValue): List[A] = {
          json.asJsObject.fields.toList.collect {
            case (k, JsString(v)) => A(k, v)
          }
        }
      }
    
      import spray.json._
    
      def main(args: Array[String]): Unit = {
        val json =
          """
            |{
            |   "one": "1",
            |   "two": "2"
            |}
          """.stripMargin
    
        val result = json.parseJson.convertTo[List[A]]
        println(result)
      }
    

    Prints:

    List(A(one,1), A(two,2))