kenlz
kenlz

Reputation: 461

JsonArray in Scala

currently this is what I could get

{
    "friends": [438737,
        12345,
        32153,
        53243
    ]
}

achievable by doing creating a case class

case class FriendsModel(uid: Option[String])
object FriendsModel {
  implicit val paramsWrite = Json.writes[FriendsModel]
  implicit val paramsRead = Json.reads[FriendsModel]
}

and basically adding the friendsModel to a List[FriendsModel] called friendList

and I could just Ok(Json.toJson(friendList))

Is there a way to insert variable as "friends" so my Json return would look like this:

{
    "123654": [438737,
        12345,
        32153,
        53243
    ]
}

where 123654 is my userid.

Upvotes: 2

Views: 1103

Answers (1)

vdebergue
vdebergue

Reputation: 2404

I would create a case class to encapsulate the data:

case class User(uid: String, friends: Seq[FriendsModel])

and create a Json writer for this type:

object User {
  implicit val writer: Writes[User] = Writes { user =>
    Json.obj(
      user.uid -> user.friends
    )
  }
}

This will get you { "123654": [438737,...] }

Upvotes: 6

Related Questions