Marshaling using spray json best case for map of maps

147 Views Asked by At

I have the following case class rows which i want to further filter and represent them as a json

case class Row(id: UUID, ownerId: UUID, typeId: UUID, name: String, value: String)

json format I want to represent in

{
  "owner": "ownerId",
  "configurations": {
    "typeId1": {
      "name1": "value1",
      "name2": "value2"
    },
    "typeId2": {
      "name3": "value3",
      "name4": "value4"
    }
  }
}

Now I'm converting this into the following result type

case class Data(owner: String, configurations: Map[String, Map[String, String]])

I'm doing the above using the following function

def convert(rows: Seq[Row]): Data =
  Data(owner = <SomedatabaseCall to populate this>,
       configurations = rows.groupMapReduce(_.typeId/*Actually need to populate this with a database call as well*/)(r => Map(r.name -> r.value))(_ ++ _))

I have three questions here :

  1. How can you marshall the Map object of Map of Maps using spray-json, I'm not able to clear that out?

  2. Now if we see the typeId is actually a UUID and I need to make another database call to find the typeName , what the best way to populate this and make the custom json object I want to create ?

  3. I can't use the groupMapReduce method since we use 2.12 version of scala and I can't upgrade for other reasons. Any alternative to group by the typeName

1

There are 1 best solutions below

0
Bunyod On

My suggestions:

  1. Use circe instead of spray-json. It has auto derivation feature that helps to you go fast without any custom/manual encoder decoder ex:
  import io.circe.generic.auto._, io.circe.syntax._
  case class Data(owner: String, configurations: Map[String, Map[String, String]])

  val data = Data("abc", Map("key1" -> Map("kkey1" -> "value1"), "key2" -> Map("kkey2" -> "value2"), "key3" -> Map("kkey2" -> "value1")))

  println(s"JSON:${data.asJson.toString()}")


  1. Not enough information for me to answer clearly
  2. Grouping. Yes, there is alternative version:
x.groupBy(key).mapValues(_.map(f).reduce(reduce))