How to use Java 8 Advanced with Moxy and Jersey

Can Jersey be used with Moxy to / from Json and Java 8 Optionals?

How do I set it up?

+3


source to share


1 answer


You can declare the following class:

public class OptionalAdapter<T> extends XmlAdapter<T, Optional<T>> {

    @Override
    public Optional<T> unmarshal(T value) throws Exception {
        return Optional.ofNullable(value);
    }

    @Override
    public T marshal(Optional<T> value) throws Exception {
        return value.orElse(null);
    }

}

      

And use like this:

@XmlRootElement
public class SampleRequest {

    @XmlElement(type = Integer.class)
    @XmlJavaTypeAdapter(value = OptionalAdapter.class)
    private Optional<Integer> id;

    @XmlElement(type = String.class)
    @XmlJavaTypeAdapter(value = OptionalAdapter.class)
    private Optional<String> text;

    /* ... */

}

      

Or declare in package-info.java

and remove @XmlJavaTypeAdapter

from POJO:

@XmlAccessorType(XmlAccessType.FIELD)
@XmlJavaTypeAdapters({
        @XmlJavaTypeAdapter(type = Optional.class, value = OptionalAdapter.class)
})

      



But here are some disadvantages:

  • The adapter above can only work with simple types like Integer, String, etc., which can be handled by MOXY by default.
  • You must specify explicitly @XmlElement(type = Integer.class)

    to tell the parser type to work, otherwise the values null

    will be passed to the method unmarshal

    .
  • You are missing out on the possibility of using adapters for custom types, eg. custom adapter for class java.util.Date

    based on some date format string. To overcome this, you need to create an adapter something like class OptionalDateAdapter<String> extends XmlAdapter<String, Optional<Date>>

    .

Also not recommended for use Optional

in the field, see this discussion .

With all of the above in mind, I would suggest simply using Optional

as the return type for your POJOs:

@XmlRootElement
public class SampleRequest {

    @XmlElement
    private Integer id;

    public Optional<Integer> getId() {
        return Optional.ofNullable(id);
    }

    public void setId(Integer id) {
        this.id = id;
    }

}

      

0


source







All Articles