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) {
        this.name = input.getString("name", null);
        this.language = input.getString("language", null);
    }

    @Override
    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 org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import org.junit.Test;

public class MappingArrayValuesTest {

    @Test
    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")).
                build();
    }

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

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: airhacks.io.


NEW MUC Airport Workshop: Migrating Java Client (Swing / Java FX) to Web Standards

Airport MUC workshops: Web (SPA, PWAs, Offline, Desktop, Mobile) Applications Essentials and Effective Web Applications. No migrations. #usetheplatform

Podcast: airhacks.fm and newsletter: airhacks.news

A book about rethinking Java EE Patterns

Comments:

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.

http://tutorials.jenkov.com/java-json/jackson-objectmapper.html

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

Post a Comment:
  • HTML Syntax: NOT allowed
realworldpatterns.com
Online Workshops
...the last 150 posts
...the last 10 comments
License