1
 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?

md samual
  • 305
  • 3
  • 15
  • Why aren't you using POST oauth2/token ? You can find its documentation at https://developer.twitter.com/en/docs/basics/authentication/api-reference/token. You can read about Json reads, and writes, which you have built-in in your play app. https://www.playframework.com/documentation/2.8.x/ScalaJsonCombinators – Tomer Shetah Jul 27 '20 at 18:17
  • So how to get user_id, screen_name, oauth_token ans oauth_secret_token. Aouth 2.0 only response access_token. – md samual Jul 27 '20 at 18:53
  • Does my answer help you? – Tomer Shetah Nov 22 '20 at 21:55

1 Answers1

0

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.

Tomer Shetah
  • 8,413
  • 7
  • 27
  • 35