Hello, noob question for ktor and json via GSON (e...
# ktor
w
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
I think it's about the answer
what you should get from that endpoint?
w
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
what if you use
Copy code
call.receiveParameters()
instead
aldo, receiveParameters are from web, not sure if you're doing the same
w
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
i think you can access params using for example
parameters["emoji"] parameters["phrase"]
w
I can do this by POSTing a JSON object?
a
🤔, not sure if you can, you could try
w
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
Cool, sorry i was offline
what was the change with
curl
?