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.


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: airhacks.fm and newsletter: airhacks.news

A book about rethinking Java EE Patterns

Comments:

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