11@file:JvmName(" APIServer" )
22
3- import com.google.gson.Gson
3+
4+
45import io.ktor.application.call
56import io.ktor.application.install
67import io.ktor.features.CallLogging
8+ import io.ktor.features.ContentNegotiation
79import io.ktor.features.DefaultHeaders
10+ import io.ktor.gson.gson
811import io.ktor.http.ContentType
912import io.ktor.request.path
13+ import io.ktor.response.respond
1014import io.ktor.response.respondText
1115import io.ktor.routing.get
1216import io.ktor.routing.routing
1317import io.ktor.server.engine.embeddedServer
1418import io.ktor.server.netty.Netty
1519import org.slf4j.event.Level
1620
21+ data class Author (val name : String , val website : String )
1722fun main (args : Array <String >) {
1823
1924 val jsonResponse = """ {
@@ -22,7 +27,6 @@ fun main(args: Array<String>) {
2227 "description": "Pay water bill today",
2328 }"""
2429
25- data class Author (val name : String , val website : String )
2630
2731 embeddedServer(Netty , 8080 ) {
2832 install(DefaultHeaders ) {
@@ -33,15 +37,18 @@ fun main(args: Array<String>) {
3337 filter { call -> call.request.path().startsWith(" /todo" ) }
3438 filter { call -> call.request.path().startsWith(" /author" ) }
3539 }
40+ install(ContentNegotiation ) {
41+ gson {
42+ setPrettyPrinting()
43+ }
44+ }
3645 routing {
3746 get(" /todo" ) {
3847 call.respondText(jsonResponse, ContentType .Application .Json )
3948 }
4049 get(" /author" ) {
4150 val author = Author (" baeldung" , " baeldung.com" )
42- val gson = Gson ()
43- val json = gson.toJson(author)
44- call.respondText(json, ContentType .Application .Json )
51+ call.respond(author)
4552
4653 }
4754
0 commit comments