2

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.

2
  • According to your code, Json.toJson(friends) should return play.api.libs.json.JsValue = [{"uid":"12"},{"uid":"13"},{"uid":"14"}], can you explain how are you getting the output you mentioned Commented Jun 23, 2016 at 12:18
  • Sorry, actually it was case class FriendsModel(uid: Option[MyCustomModel]) Commented Jun 24, 2016 at 2:45

1 Answer 1

6

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,...] }

Sign up to request clarification or add additional context in comments.

2 Comments

Every time you want to get rid of field names you will need to implement a custom writer, as stated in this answer
Thanks! this confirmed the result!

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.