Private Fields Serialization with JSON-B and JAX-RS 2.1 / Java EE 8

JSON-B from Java EE 8 serializes public fields or properties as default. For private field serialization:

public class Workshop {

    private String name;
    private int duration;

    public Workshop(String name, int duration) { = name;
        this.duration = duration;


you will have to implement a PropertyVisibilityStrategy (checkout Java EE 8: Serializing POJOs with JSON-B):

    public class PrivateVisibilityStrategy implements PropertyVisibilityStrategy {
        public boolean isVisible(Field field) {
            return true;
        public boolean isVisible(Method method) {
            return false;

...pass your custom configuration to the JsonbBuilder and return the instance with a ContextResolver:

    import javax.json.bind.Jsonb;
    import javax.json.bind.JsonbBuilder;
    import javax.json.bind.JsonbConfig;
    public class JSONConfigurator implements ContextResolver {
        public Jsonb getContext(Class type) {
            JsonbConfig config = new JsonbConfig().
                    withPropertyVisibilityStrategy(new PrivateVisibilityStrategy());
            return JsonbBuilder.newBuilder().

Now your POJO's private fields are going to be used for JSON-mapping:

public class WorkshopsResource {

    public Workshop workshop() {
        return new Workshop("Java EE 8", 42);


Result: {"duration":42,"name":"Java EE 8"}

Tested with Payara 5.

See you at Java EE Workshops at MUC Airport, particularly at the Effective Java EE 8 workshop

NEW: Online Workhop Effective WebApps without Frameworks is also coming to: MUC Airport.

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

Podcast: and newsletter:

A book about rethinking Java EE Patterns


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