https://kotlinlang.org logo
#ktor
Title
# ktor
w

waltermcq

02/25/2020, 9:12 PM
Hello, noob question for ktor and json via GSON (edit: solved)
as per the samples I added GSON for content negotiation
Copy code
install(ContentNegotiation) {
        gson {
            setDateFormat(DateFormat.LONG)
            setPrettyPrinting()
        }
    }
I created an extension function to catch post requests to an endpoint
Copy code
fun Route.phrase(db: Repository) {    //db param adheres to repository interface
    post(PHRASE_ENDPOINT) {
        // get request from call, then
        val request = call.receive<Request>()
        // add on db, then
        val phrase = db.add(EmojiPhrase(request.emoji, request.phrase))
        // respond to call, sending back emoji phrase that was added to repository
        println("post: ${phrase.phrase} ${phrase.emoji}}")
        call.respondText("post received", contentType = ContentType.Text.Plain)
    }
}
I made a post request using curl
Copy code
curl -X POST -H "Content-Type: application/json" -d tmp/request2.json <http://localhost:8080/api/v1/phrase>
this is the json file I am POSTing
Copy code
{
  "emoji": "1234",
  "phrase": "test"
}
I get a server error when I try this:
java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $%
It looks like this error is coming from the
call.receive<Request>()
call What am I doing wrong?
a

Alejandro Rios

02/25/2020, 9:26 PM
I think it's about the answer
what you should get from that endpoint?
w

waltermcq

02/25/2020, 9:28 PM
Well, in the above code it just responds with the same json that was sent
but if I comment out the respond I still get that error
so as I said above I think its the >call.receive<Request>()
a

Alejandro Rios

02/25/2020, 9:47 PM
what if you use
Copy code
call.receiveParameters()
instead
aldo, receiveParameters are from web, not sure if you're doing the same
w

waltermcq

02/25/2020, 9:49 PM
Wouldn't
parameters
here mean what is in the query string? I'm trying to send json data, how would I do that with parameters..?
a

Alejandro Rios

02/25/2020, 9:56 PM
i think you can access params using for example
parameters["emoji"] parameters["phrase"]
w

waltermcq

02/25/2020, 9:56 PM
I can do this by POSTing a JSON object?
a

Alejandro Rios

02/25/2020, 9:57 PM
🤔, not sure if you can, you could try
w

waltermcq

02/25/2020, 10:14 PM
I think something is wrong with my curl command and/or the actual JSON file I was trying to send
which would explain the error since it is referencing that its expecting a
{
but is getting
"
I changed my curl request and now it works!
(case closed)
a

Alejandro Rios

02/26/2020, 1:46 AM
Cool, sorry i was offline
what was the change with
curl
?
11 Views