在JSON中将日期发送到REST服务

时间:2018-04-03 17:36:59

标签: java json rest date jax-rs

我正在使用Java-EE中的REST接口开发CRUD应用程序。

我有一些包含日期字段的实体。当我想在请求体中使用带有JSON的POST请求创建这样一个实体的实例时,jax-rs(或底层反序列化器)会抱怨解析日期部分。

这是我得到的例外:

  

用于servlet服务的Servlet.service().JAXRSConfiguration抛出   exception java.time.format.DateTimeParseException:Text' 2011-11-11'   无法在索引10处解析

我试图在请求中发送此信息:

{
    "title": "testTitle",
    "description": "testDescription",
    "playtime": 50,
    "creationDate": "2011-11-11"
}

如何在json中定义日期以使其成功解析?哪种格式正确?

这是实体类:

@Entity
@NamedQueries({
        @NamedQuery(name = "Movie.findAll", query = "SELECT m FROM Movie m")
})
public class Movie extends AbstractDao{

    private String title;

    private String description;

    @ManyToMany(mappedBy = "movies")
    private List<Actor> actors;

    @ManyToMany(mappedBy = "movies")
    private List<Director> directors;

    private int playtime;

    @OneToOne(cascade = CascadeType.PERSIST)
    private Trailer trailer;

    @Temporal(value = TemporalType.DATE)
    private Date creationDate;

getters,setters, etc

这是jax-rs服务:

@Path("/movies")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class MovieRestService {

    @Inject
    private MovieService movieService;

    @GET
    public List<Movie> getMovies(){
        return movieService.findAll();
    }

    @Path("{id}")
    @GET
    public Movie getMovie(@PathParam("id") long id){
        return movieService.findById(id);
    }

    @POST
    public Movie addMovie(Movie movie){
        return movieService.create(movie);
    }

    @Path("{id}")
    @PUT
    public Movie updateMovie(Movie movie, @PathParam("id") long id){
        return movieService.update(movie,id);
    }

    @Path("{id}")
    @DELETE
    public Movie deleteMovie(@PathParam("id") long id){
        return movieService.delete(id);
    }

}

1 个答案:

答案 0 :(得分:0)

尝试使用类似以下的DateAdapter(XmlAdapter):

并注释:

@XmlJavaTypeAdapter(DateAdapter.class)
private Date creationDate;

您还可以在creationDate的getter中注释

班级:

import java.text.SimpleDateFormat;
import java.util.Date;

import javax.xml.bind.annotation.adapters.XmlAdapter;

public class DateAdapter extends XmlAdapter<String, Date> {
  private static final TimeZone UTC = TimeZone.getTimeZone("UTC");    
  private static final String PATTERN_T_WITH_SEC = "yyyy-MM-dd'T'HH:mm:ss";
  private SimpleDateFormat dateFormat = new impleDateFormat(PATTERN_T_WITH_SEC);

@Override
public String marshal(Date v) throws Exception {
    dateFormat.setTimeZone(UTC);
    String dateF = dateFormat.format(v);
    return dateF;
}

@Override
public Date unmarshal(String v) throws Exception {
    dateFormat.setTimeZone(UTC);
    Date date = dateFormat.parse(v);
    return date;
}

}