Jtoml

TOML for Java

This is a parser for Tom Preson-Werner‘s (@mojombo) [TOML][1] markup language, using Java.

GitHub project

You can browse the project on my GitHub repository [@agrison/jtoml][2].

Usage

Parsing

// parse from a String or from a File
Toml toml = Toml.parse("pi = 3.14\nfoo = \"bar\"");
toml = Toml.parse(new File("foo.toml"));

Getting values

// get different types
toml.get("foo");
toml.getString("foo");
toml.getBoolean("foo");
toml.getDate("foo");
toml.getDouble("foo");
toml.getLong("foo");
toml.getList("foo");
toml.getMap("foo");

Mapping custom types

You can map a custom type from an entire TOML String or part of it.

Let‘s say you would like to map the following TOML to a `Player` entity.

[player]
nickName = "foo"
score = 42

You could do it as simple as following:

// or Custom objects
public class Player {
    String name;
    Long score;
}
Toml toml = Toml.parse("[player]\nname = \"foo\"\nscore = 42");
Player player = toml.getAs("player", Player.class);
player.name; // "foo"
player.score; // 42L

Note: Supported types are Long, String, Double, Boolean, Calendar, List, Map or Objects having the pre-cited types only.

Serialization

JToml supports also serialization. Indeed, you can serialize a custom type to a String having TOML format representing the original object.

Imagine the following custom Objects:

public class Stats {
    Long maxSpeed;
    Double weight;
    // Constructors
}

public class Car {
    String brand;
    String model;
    Stats stats;
    Boolean legendary;
    Calendar date;
    List<String> options;
    // Constructors
}

Car f12Berlinetta = new Car("Ferrari", "F12 Berlinetta", true, "2012-02-29",
    360, 1525.5, Arrays.asList("GPS", "Leather", "Nitro")
);
String toml = Toml.serialize("f12b", f12Berlinetta);

The call to Toml.serialize() will produce the following TOML format:

[f12b]
brand = "Ferrari"
model = "F12 Berlinetta"
legendary = true
date = 2012-02-29T00:00:00Z
options = ["GPS", "Leather", "Nitro"]

[f12b.stats]
maxSpeed = 347
weight = 1525.5

You can also serialize the current instance of a Toml object:

Toml toml = Toml.parse("[player]\nname = \"foo\"\nscore = 42");
toml.serialize();

Will produce the following TOML String

[player]
name = "foo"
score = 42

Note: Like for custom types above, supported types are Long, String, Double, Boolean, Calendar, List, Map or Objects having the pre-cited types only.

Todo

  • New parsers using Parboiled and/or ANTLR.

License

MIT

Alexandre Grison - //grison.me - @algrison