Java EE 8 / JSON-P 1.1: Convenient JsonArray to POJO conversion 📎
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.