Search code examples
jsonscalascalaj-http

How do I post json data in scalaj?


I am using scalaj to make a Http post request

How can I pass lat,long and radius as arguments in the postData field

val result = Http("http:xxxx/xxx/xxxxx").postData("""{"latitude":"39.6270025","longitude":"-90.1994042","radius":"0"}""").asString

Why is the string passed in """json""" such a manner?

Based on the docs it looks like the postData function takes only array of bytes and string as argument.


Solution

  • So this is two questions at once. Let's start with the second one.

    Why is the string passed in """json""" such a manner?

    Scala allows special syntax for multiline string literals (or strings containing newlines, quotation marks and so on). So you can do

    val s = """Welcome home!
               How are you today?"""
    

    Now back to the main question

    How can I pass lat, long and radius as arguments in the postData field?

    I suppose you are in this situation:

    val lat = "39.6270025"
    val long = "-90.1994042"
    

    And you want to pass that into the postData function, mixed with some other maybe fixed strings.

    Well another feature Scala gives is so-called string interpolation. Easy example

    val name = "Mark" // output on the REPL would be: name: String = Mark
    val greeting = s"Hello $name!" // output on the REPL would be: greeting: String = Hello Mark!
    

    So in your case you could do the same

    val result = Http("http:xxxx/xxx/xxxxx")
      .postData(s"""{"latitude":$lat,"longitude":$long,"radius":"0"}""")
      .asString