adam bien's blog

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) {
        this.name = 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 {
    
        @Override
        public boolean isVisible(Field field) {
            return true;
        }
    
        @Override
        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;
    import javax.ws.rs.ext.ContextResolver;
    import javax.ws.rs.ext.Provider;
    
    @Provider
    public class JSONConfigurator implements ContextResolver {
    
        @Override
        public Jsonb getContext(Class type) {
            JsonbConfig config = new JsonbConfig().
                    withPropertyVisibilityStrategy(new PrivateVisibilityStrategy());
            return JsonbBuilder.newBuilder().
                    withConfig(config).
                    build();
        }
    }

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


@Path("workshops")
public class WorkshopsResource {

    @GET
    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