Search code examples
scalaplayframeworkplay-json

How do you parse string from arraybuffer to double using Scala?


I'm trying to map string to double from an ArrayBuffer that I parsed through Playframework but I keep getting the following error:

Exception in thread "main" java.lang.NumberFormatException: For input string: ""0.04245800""

I'm not sure why it's doing this and I'm new to Scala coming from Python background.

import org.apache.http.client.methods.HttpGet

import play.api.libs.json._
import org.apache.http.impl.client.DefaultHttpClient


object main extends App {
  val url = "https://api.binance.com/api/v1/aggTrades?symbol=ETHBTC"

  val httpClient = new DefaultHttpClient()
  val httpResponse = httpClient.execute(new HttpGet(url))
  val entity = httpResponse.getEntity()
  val content = ""

  if (entity !=null) {
    val inputStream = entity.getContent()
    val result = io.Source.fromInputStream(inputStream).getLines.mkString
inputStream.close

    println("REST API: " + url)
    val json: JsValue = Json.parse(result)


    var prices = (json\\"p")

    println(prices.map(_.toString()).map(_.toDouble))

  }
}

Solution

  • If you know for sure your list contains only strings you can cast them like this, and use the 'original' value to get the Double value from:

    println(prices.map(_.as[JsString].value.toDouble))
    

    As JsString is not a String you cannot call toDouble on that.

    Just for completeness: If you are not certain your list contains only strings you should add an instanceof check or pattern matching.