How it works...

First, the loadFromArray() method:

    private void loadFromArray(){
JsonArray array = BUILDERFACTORY.createArrayBuilder()
.add(BUILDERFACTORY.createObjectBuilder()
.add("name", "User1")
.add("email", "[email protected]"))
.add(BUILDERFACTORY.createObjectBuilder()
.add("name", "User2")
.add("email", "[email protected]"))
.add(BUILDERFACTORY.createObjectBuilder()
.add("name", "User3")
.add("email", "[email protected]"))
.build();
fromArray = jsonbBuilder.toJson(array);
}

It uses the BuilderFactory and the createArrayBuilder method to easily build an array of JSONs (each call of createObjectBuilder creates another array member). At the end, we use the JSON-B to convert it to a JSON string:

    private void loadFromStructure(){
JsonStructure structure = BUILDERFACTORY.createObjectBuilder()
.add("name", "User1")
.add("email", "[email protected]")
.add("profiles", BUILDERFACTORY.createArrayBuilder()
.add(BUILDERFACTORY.createObjectBuilder()
.add("id", "1")
.add("name", "Profile1"))
.add(BUILDERFACTORY.createObjectBuilder()
.add("id", "2")
.add("name", "Profile2")))
.build();
fromStructure = jsonbBuilder.toJson(structure);

JsonPointer pointer = new JsonPointerImpl("/profiles");
JsonValue value = pointer.getValue(structure);
fromJpointer = value.toString();
}

Here, instead of an array, we are building a single JSON structure. Again, we use JSON-B to convert the JsonStructure to a JSON string.

We also took advantage of having this JsonStructure ready and used it to query the user profiles using the JsonPointer object:

private void loadFromUser(){
User user = new User("Elder Moraes", "[email protected]",
new Integer[]{1,2,3});
fromUser = jsonbBuilder.toJson(user);
}

And here was the simplest: creating an object and asking JSON-B to convert it to a JSON string.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.120.136