JAXB With Kotlin

Kotlin is a programming language that runs on the Java Virtual Machine (JVM) and is designed to interoperate with Java code and thus with the existing frameworks.

For the purpose of this tutorial let’s imagine we develop a library application. As a first step let’s define a class that represents a book. A book has a name, author and description

About the Kotlin language: More on classes

As a second step let’s marshal a Book just to make sure everything is working:

About the Kotlin language: More on functions

Note: Here you can find more information on the Book::class.java expression

Running the application shows an error stating that: unable to marshal type "Book" as an element because it is missing an @XmlRootElement annotation Let’s add that annotation to the Book class and run the application again – this time another error is printed: Book does not have a no-arg default constructor. When we added the Book class we declared only one constructor (the primary one) which has three arguments. Let’s add another one in order to make JAXB happy:

The new constructor calls the primary one with default values. Kotlin has special opinion on null values (see here) and the developer must specially declare the null possibility. Since I agree that null should be avoided as a value, default values are provided in this case. Let’s run the application again. This time the output is:

The book element is empty because we didn’t add @XmlElement to the fields we want to marshal and we did not tell JAXB how to access the properties. Let’s fix that:

And here is the output:

So far so good. We have a working marshaling of a Book. Let’s organize books in a Library by adding a new class that will hold a collection of Books:

About the Kotlin language: More on collections

This time the library name won’t be an element but an attribute. Let’s marshal it:

And here is the output:

About the Kotlin language: More on try-with-resource

Let’s unmarshal it and print the contents of the Library

(yes Kotlin supports multi-line strings. It’s omitted here in sake of brevity)
Note:Since the Unmarshaller returns Object (not always but in this case it does) but we expect Library object then we use “unsafe” cast with as
This is the output:


3 thoughts on “JAXB With Kotlin”

  1. Thank you, this was helpful! However, this does not work properly for me (with Kotlin 1.1.2-2): The @XmlElement annotations on the parameters of the Book class do not have any effect. You can see this by providing a name or a namespace (i.e. @XmlElement(name=”title”)). Luckily, annotations on properties (like you did in the Library class) work perfectly.

Leave a Reply

Your email address will not be published. Required fields are marked *