Unmarshalling LocalDate/LocalDateTime with MOXy

2019-03-06 04:25发布

问题:

How can I get MOXy to unmarshal JSON into LocalDate and LocalDateTime?

I've got an @GET method which produces a sample instance with three fields of types LocalDate, LocalDateTime and Date, respectively.

Hitting that endpoint, I get:

{
    "localDate": "2017-07-11",
    "localDateTime": "2017-07-11T10:11:10.817",
    "date": "2017-07-11T10:11:10.817+02:00"
}

I then POST the above data to my @POST method, which simply returns the data again:

{
    "date": "2017-07-11T10:11:10.817+02:00"
}

As you can see, both localDate and localDateTime are lost in the process, because MOXy does not initialize those two fields.

What gives? MOXy seems to support serialization of these types, but not deserialization?

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;

@Path("/test/date")
public class DateTest {
    public static class Data {
        public LocalDate localDate;
        public LocalDateTime localDateTime;
        public Date date;
    }

    @GET
    @Path("roundtrip")
    public Response roundtrip() {
        Data sample = getSample();
        return roundtrip(sample);
    }

    @POST
    @Path("roundtrip")
    @Consumes(MediaType.APPLICATION_JSON)
    public Response roundtrip(Data t) {
        return Response.status(Response.Status.OK).entity(t).build();
    }

    protected Data getSample() {
        final Data data = new Data();
        data.localDate = LocalDate.now();
        data.localDateTime = LocalDateTime.now();
        data.date = new Date();
        return data;
    }
}

Moxy version: jersey-media-moxy-2.25.1

回答1:

According to peeskillet's suggestion I implemented the following adapter class:

public class LocalDateTimeAdapter extends XmlAdapter<String, LocalDateTime>{

  private static final DateTimeFormatter DTF = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");

  @Override
  public String marshal(LocalDateTime localDateTime) throws Exception {
    return localDateTime.format(DTF);
  }

  @Override
  public LocalDateTime unmarshal(String string) throws Exception {
    return LocalDateTime.parse(string, DTF);
  }

}

In addition, I created package-info.java in the same package where my classes for MOXy and the adapter (in a subpackage) are located with the following content:

@XmlJavaTypeAdapters({
  @XmlJavaTypeAdapter(type=LocalDateTime.class,
      value=LocalDateTimeAdapter.class)
})
package api;

import java.time.LocalDateTime;

import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapters;

import api.adapter.LocalDateTimeAdapter;

Thus, marshalling and unmarshalling works without problems. And with DTF you can specify the format that shall be applied.