sebastiandaschner blog


Hacking with the JSONB 1.0 Public Review

#javaee wednesday, june 29, 2016

The Public Review of JSR 367 (JSONB 1.0) has just recently been announced. The snapshot version can already be tested.

For an example see the jsonb module of my JAX-RS Hypermedia project.

As JSONB — provided by the reference implementation — can’t obviously be integrated in JAX-RS yet, we need some boilerplate code in the JAX-RS resource methods.

See the CartResource class as an example:

@Path("shopping_cart")
public class CartResource {

    ...

    // JAX-RS 2.0 obviously isn't integrated with JSONB yet
    private Jsonb jsonb;

    // as deserialization is done manually, validation also isn't integrated by JAX-RS
    @Inject
    Validator validator;

    @PostConstruct
    public void initJsonb() {
        jsonb = JsonbBuilder.create();
    }

    @GET
    public StreamingOutput getShoppingCart() {
        final ShoppingCart cart = shoppingCart.getShoppingCart();
        ...

        return output -> jsonb.toJson(cart, output);
    }

    @POST
    public void addItem(InputStream input) {
        final CartInsertion insertion = jsonb.fromJson(input, CartInsertion.class);

        final Set<ConstraintViolation<CartUpdate>> violations = validator.validate(insertion);
        if (!violations.isEmpty())
            throwBadRequest(violations);

        ...
    }
}

This shows us very well, what’s one of the most important benefits of using Java EE: Being able to seemlessly integrate various specifications — without these extra efforts of course — as soon as the new specs are final and incorporated.

 

Found the post useful? Subscribe to my newsletter for more free content, tips and tricks on IT & Java: