Skip to content
Advertisement

How to parse TOML document with Java

In my Java app I get a TOML document from REST service response as String and I look how to parse it and convert to Java objects.

Ideally I’d like to use some existing mapper library for deserialization, something like Jackson or Gson for JSON objects. Are there any options in Java ecosystem for that?

Advertisement

Answer

There are several libraries to work with TOML files in Java, such as mwanji/toml4j and tomlj/tomlj. The toml4j looks more maintained and has the ability to map the TOML file to your POJO classes, so it should perfectly match your needs.

From its documentation:

Toml#to(Class<T>) maps a Toml instance to the given class.

TOML file example:

name = "Mwanji Ezana"

[address]
  street = "123 A Street"
  city = "AnyVille"
  
[contacts]
  "email address" = "me@example.com"

POJO classes example:

class Address {
  String street;
  String city;
}

class User {
  String name;
  Address address;
  Map<String, Object> contacts;
}

How to map TOML file to POJO classes:

User user = new Toml().read(tomlFile).to(User.class);

assert user.name.equals("Mwanji Ezana");
assert user.address.street.equals("123 A Street");
assert user.contacts.get(""email address"").equals("me@example.com");
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement