Java EE 8 / JSON-P 1.1: Convenient JsonArray to POJO conversion

With the JSON-P 1.1 / Java EE 8 method: getValueAs a JsonArray instance can be directly converted into a POJO-List. The POJO's constructor:

import javax.json.JsonObject;

public class Developer {

    private String name;
    private String language;

    public Developer(JsonObject input) { = input.getString("name", null);
        this.language = input.getString("language", null);

    public String toString() {
        return "Developer{" + "name=" + name + ", language=" + language + '}';

...can be used as the converter function / parameter of getValueAs:

import java.util.List;
import javax.json.Json;
import javax.json.JsonArray;
import javax.json.JsonObject;
import static;
import static org.junit.Assert.assertThat;
import org.junit.Test;

public class MappingArrayValuesTest {

    public void map() {
        JsonArray developerArray = getDevelopers();
        List<Developer> developers = developerArray.getValuesAs(Developer::new);
        assertThat(developers.size(), is(2));
        System.out.println("developers = " + developers);

    JsonArray getDevelopers() {
        return Json.createArrayBuilder().
                add(create("brendan", "JavaScript")).
                add(create("james", "Java")).

    JsonObject create(String name, String language) {
        return Json.createObjectBuilder().
                add("name", name).
                add("language", language).

The successful test outputs: developers = [Developer{name=brendan, language=JavaScript}, Developer{name=james, language=Java}]

See you at Java EE Workshops at Munich Airport, Terminal 2 or Virtual Dedicated Workshops / consulting. Is Munich's airport too far? Learn from home:


Sorry if I don't quite see the advantage of this approach.

Why would I pollute my POJO with JSON dependencies?

Using automated mapping with the Jackson ObjectMapper seems more intuitive to me.

Posted by Christof on April 27, 2018 at 05:24 PM CEST #

Post a Comment:
  • HTML Syntax: NOT allowed
...the last 150 posts
...the last 10 comments