How to convert response body in Json using play framework

1k Views Asked by At
 override def accessToken(): ServiceCall[RequestTokenLogIn, Done] = {
request=>
  val a=request.oauth_token.get
  val b=request.oauth_verifier.get
  val url=s"https://api.twitter.com/oauth/access_token?oauth_token=$a&oauth_verifier=$b"
  ws.url(url).withMethod("POST").get().map{
    res=>
   println(res.body)
  }

The output which I am getting on terminal is
oauth_token=xxxxxxxxx&oauth_token_secret=xxxxxxx&user_id=xxxxxxxxx&screen_name=xxxxx

I want to convert this response in json format.like

{
oauth_token:"",
token_secret:"",
}

When Calling res.json.toString its not converting into jsValue. Is there any other way or am I missing something?

1

There are 1 best solutions below

0
On

According to the documentation twitter publishes, it seems that the response is not a valid json. Therefore you cannot convert it automagically. As I see it you have 2 options, which you are not going to like. In both options you have to do string manipulations.

The first option, which I like less, is actually building the json:

print(s"""{ \n\t"${res.body.replace("=", "\": \"").replace("&", "\"\n\t\"")}" \n}""")

The second option, is to extract the variables into a case class, and let play-json build the json string for you:

case class TwitterAuthToken(oauth_token: String, oauth_token_secret: String, user_id: Long, screen_name: String)
object TwitterAuthToken {
  implicit val format: OFormat[TwitterAuthToken] = Json.format[TwitterAuthToken]
}
 
val splitResponse = res.body.split('&').map(_.split('=')).map(pair => (pair(0), pair(1))).toMap
val twitterAuthToken = TwitterAuthToken(
  oauth_token = splitResponse("oauth_token"),
  oauth_token_secret = splitResponse("oauth_token_secret"),
  user_id = splitResponse("user_id").toLong,
  screen_name = splitResponse("screen_name")
)

print(Json.toJsObject(twitterAuthToken))

I'll note that Json.toJsObject(twitterAuthToken) returns JsObject, which you can serialize, and deserialize.

I am not familiar with any option to modify the delimiters of the json being parsed by play-json. Given an existing json you can manipulate the paths from the json into the case class. But that is not what you are seeking for.

I am not sure if it is requires, but in the second option you can define user_id as long, which is harder in the first option.