Harald Pehl

Developer notes written down before they get lost.

JSON Mapping in Piriti

Following a proposal by Jerome Louvel, I added JSON mapping to Piriti. Piriti is a JSON / XML mapper for GWT based on annotations and deferred binding.

To map JSON data you have to annotate your model classes with @JsonField annotations. In case you have the following JSON structure:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
{
    isbn: "978-0345417954",
    pages: 432,
    title: "The Hotel New Hampshire",
    author: {
        firstname: "John",
        surname: "Irving",
    },
    reviews: [
        "A hectic gaudy saga with the verve of a Marx Brothers movie.",
        "Rejoice! John Irving has written another book according to your world.",
        "Spellbinding, intensely human, a high-wire act of dazzling virtuosity."
    ]
}

You can use the following code to map the JSON data to your model:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public class Book
{
    interface BookReader extends JsonReader<Book> {}
    public static final BookReader JSON = GWT.create(BookReader.class);

    @JsonField String isbn;
    @JsonField int pages;
    @JsonField String title;
    @JsonField Author author;
    @JsonField List<String> reviews;
}

...

public class Author
{
    interface AuthorReader extends JsonReader<Author> {}
    public static final AuthorReader JSON = GWT.create(AuthorReader.class);

    @JsonField String firstname;
    @JsonField String surname;
}

...

String jsonString = ...; // The JSON structure (see above) 
Book book = Book.JSON.read(jsonString);

To learn more about piriti take a look at https://github.com/hpehl/piriti.