javajakarta-eejsonb-api

How to unmarshal / deserialize collections without setters with JSON-B


I like to write my POJOs not to have setters for collections.

public class Parent {
    private List<Child> children;
    public List<Child> getChildren() {
        if (children == null) {
            children = new ArrayList<Child>();
        }
        return children;
    }
}

// use case example
public class ParentDecorator {
    private final Parent parent;
    public ParentDecorator(Parent parent) {
        this.parent = parent;
    }
    public void addAll(List<Child> children) {
        parent.getChildren().addAll(children);
    }
}

JSON-B serialization works fine, but deserialization does not work as there is no setter for children.

Question: how should I fix this?


Solution

  • Adam Bien wrote a good article Private Fields Serialization with JSON-B and JAX-RS 2.1 / Java EE 8 which I thought would fix it. The idea is to implement a custom PropertyVisibilityStrategy for private fields. Unfortunately it didn't work in my situation for some reason.

    I made a small change to Adam's code and changed also the methods to be visible. Now my collections are deserialized.

    /**
     * JSON-B visibility strategy for deserialization.
     * 
     * Enables JSON binding of private fields without a setter.
     */
    public class JsonDeserializationStrategy implements PropertyVisibilityStrategy {
    
        @Override
        public boolean isVisible(Field field) {
            return true;
        }
    
        @Override
        public boolean isVisible(Method method) {
            return true;
        }
    }
    

    I only use this PropertyVisibilityStrategy for deserialization as the name suggests. Serialization is done with default configuration.