adam bien's blog

Java EE 8, JSON-B and java.util.Optional Serialization and Deserialization 📎

A class with java.util.Optional field:

public class MessageWithOptionalField {

    private String content;
    private Optional<String> optionalInfo;

    public MessageWithOptionalField() {

    }


    public MessageWithOptionalField(String content) {
        this.content = content;
        this.optionalInfo = Optional.empty();
    }

    public MessageWithOptionalField(String content, String optionalInfo) {
        this.content = content;
        this.optionalInfo = Optional.of(optionalInfo);
    }
    
    public String toString() {
        return "MessageWithOptionalField{" + "content=" + content + ", optionalInfo=" + optionalInfo + '}';
    }
}        

...serializes into JSON using JSON-B and PrivateVisibilityStrategy (omitting superfluous accessors) via JAX-RS resource:


@GET
public List<MessageWithOptionalField> messageWithOptional() {
    return Arrays.asList(new MessageWithOptionalField("hello without world"), new MessageWithOptionalField("hello", "world"));
}  
into the following JSON string:

[{"content":"hello without world"},{"content":"hello","optionalInfo":"world"}]    
The deserialization from a json without the optional field, e.g. {"content":"hello"} and e.g. using the following JAX-RS endpoint:

@POST
public String save(MessageWithOptionalField message) {
    return message.toString();
}

yields: MessageWithOptionalField{content=hello, optionalInfo=null}

A json string containing the optional value: {"content":"hello","optionalInfo":"world"} yields: MessageWithOptionalField{content=hello, optionalInfo=Optional[world]}

See you at Web, MicroProfile and Java EE Workshops at Munich Airport, Terminal 2 or Virtual Dedicated Workshops / consulting. Is Munich's airport too far? Learn from home: airhacks.io.