0

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 Answers 2

1

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"))
         )
      } 
    )
Sign up to request clarification or add additional context in comments.

Comments

1

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
    )
  }

1 Comment

Good Example @gharll but Try to make it safer on JSON validation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.