0
votes

I'm new to Scala and I'm learning Scala and Play Framework: I'm trying to dynamically create a Json with play/scala starting from a sequence of data named "tables" by using Map(...), List(...) and Json.toJson(...). My result should be like the code resultCustomJsonData shown below

var resultCustomJsonData = [
  {
    text: "Parent 1",
    nodes: [
      {
        text: "Child 1",
        nodes: [
          {
            text: "Grandchild 1"
          },
          {
            text: "Grandchild 2"
          }
        ]
      },
      {
        text: "Child 2"
      }
    ]
  },
  {
    text: "Parent 2"
  },
  {
    text: "Parent 3"
  },
  {
    text: "Parent 4"
  },
  {
    text: "Parent 5"
  }
];

my scala code is this below:

val customJsonData = Json.toJson(
      tables.map { t => {
        Map(
          "text" -> t.table.name.name, "icon" -> "fa fa-cube", "nodes" -> List (
              Map( "text" -> "properties" )
          )
        )
      }}
    )

but i'm getting this error:

No Json serializer found for type Seq[scala.collection.immutable.Map[String,java.io.Serializable]]. Try to implement an implicit Writes or Format for this type.
2

2 Answers

1
votes

Here is a way to do it without using temporary Map:

import play.api.libs.json.Json

val customJsonData = Json.toJson(
      tables.map { t =>  
        Json.obj( 
         "text" -> t.table.name.name, 
         "icon" -> "fa fa-cube",
         "nodes" -> Json.arr(Json.obj("text" -> "properties"))
         )
      } 
    )
1
votes

I think you should try implement custom serializer/writer. Check here.

For example:

  implicit val userWrites = new Writes[User] {
    def writes(user: User) = Json.obj(
      "id" -> user.id,
      "email" -> user.email,
      "firstName" -> user.firstName,
      "lastName" -> user.lastName
    )
  }