Nerd For Tech
Published in

Nerd For Tech

Serialize JSON HttpResponse to Kotlin Objects with Ktor.

Photo by Tom Crew on Unsplash

Jenkins API call with Ktor

Required Dependencies

Defining the HttpClient

Serializing Objects to Strings and reversed

Let’s start with a really easy example first and then go to the more difficult ones.

  1. create serializable data class
data class Data(val a: Int, val b: String)
Json.encodeToString(Data(42, "str"))
val obj = Json.decodeFromString<Data>("""{"a":42, "b": "str"}""")

Creating serializable data classes

Since our Jenkins Json response will look something like this, we need to create classes for everything we want to serialize.

  1. First of all, we need to create a root class, that contains all the other stuff. In this case I called it JenkinsJsonData.
  2. The next step what we need to have is the actions. It contains an array of elements in it.
  3. The last thing we wanna have is the lastBuiltRevision, which contains the SHA1 hash.

Call the Jenkins Api and serialize the output

  1. Double encode the branchName for the Jenkins Api call.
  2. call client.get function with the generated URL.
  3. This function needs to be in a runBlocking block because it is a suspend function.
  4. This will return a JenkinsJsonData object with the custom getter for the hash.
  5. If the status code is over 300, the get request will throw an exception and a new custom Exception will be thrown.


What went good?

The serialization by itself worked pretty good and the examples on the official documentation were pretty easy to understand and extend. Also, the get Request with Ktor worked pretty good.

What needs improvement?

The reading out of the HttpResponse was causing some trouble, because I had to use the runBlocking block to run it, since it is a suspend function. I didn’t know what such a function was or what it makes special.



NFT is an Educational Media House. Our mission is to bring the invaluable knowledge and experiences of experts from all over the world to the novice. To know more about us, visit

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store