如何使用JSON在Spring Rest中接收和发送日期?

时间:2016-07-14 01:22:18

标签: java json spring rest datetime

我现在在一个项目中工作,我一直在尝试接收并以Json形式发送日期并将其存储在我的模型/数据库上。

我的模型是这样的:

@Entity
public class Incident  {
    @Id
    private String id; //it contains sometimes letters, thats why its String

    @Column(nullable = false)
    private String responsible;

    @Temporal(TemporalType.TIMESTAMP)
    @Column(nullable = false)
    private Date uploadDate;

    @Temporal(TemporalType.TIMESTAMP)
    @Column(nullable = false)
    private Date lastDate;
}

我希望收到一个事件列表,当所有这些日期都是字符串(仅用于测试)时,它会正常工作。

但现在我希望将它们全部传递给Date。 我的当前格式从每个日期列更改,例如, uploadDate收到" dd.MM.yyyy HH:mm:ss"并收到lastDate作为" dd.MM.yyyy HH:mm"(没有秒数)。

我在控制器的 POST是:

@RequestMapping(method = RequestMethod.POST)
    @ResponseStatus(HttpStatus.CREATED)
    public @ResponseBody List<Incident> create(@RequestBody List<Incident> incident) {
         for(.....//runs all the list and insert one by one)
         {
              IncidentDao.createIncident(incident_item);
         }
         return incident;
}

DAO

@Transactional
    public Incident createIncident(Incident incident){
        em.persist(incident);
        return incident;
    }

我应该怎么做我的json发送我之前说过的方式,接受某种格式,有些人序列化它,但我希望以它的格式接收它。

在将类型更改为日期之前,所有工作都已完成。 我想我应该将@DateTimeFormat与模式一起使用,但我真的不知道在哪里放置它,如果它在模型中或在控制器/ DAO中,或者它在所有内容中。< / em>

我的 GET 就像这样 DAO

public Incident getIncidentById(String id){
        Incident incident = em.find(Incident.class, id);
        return incident;
    }

控制器

@RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public @ResponseBody Incident findById(@PathVariable String id) {
        return taskDao.getIncidentById(id);
    }

我的获取,它会在DAO返回e nothing事件列表:

public Collection<Incident> getAllIncidents(){
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<Incident> criteria = cb.createQuery(Incident.class);
        Collection<Incident> resultList = em.createQuery(criteria).getResultList();
        return resultList;
    }

控制器

@RequestMapping(method = RequestMethod.GET)
    public @ResponseBody Collection<Incident> findAll() {
        return IncidentDAO.getAllIncidents();
    }

另外我想知道如果我的一个日期也是Id,它会改变解决方案的内容(POST部分和GET部分 - 除了我应该在模型时创建的类ID有多个身份证明

感谢您的帮助,祝您度过愉快的一天!

2 个答案:

答案 0 :(得分:1)

  

uploadDate收到&#34; dd.MM.yyyy HH:mm:ss&#34;和lastDate收到&#34; dd.MM.yyyy HH:mm&#34;(没有秒)。

这实际上并没有多大意义。如果您想以您希望的方式显示日期,请在视图中设置日期格式。在您的数据库中或处理日期时,只需保留原样。

  

如果我的一个日期也是Id,那么它将会改变   溶液

嗯,这也许不是一个好主意。抱歉。你有很多ID生成选项,为什么还要使用日期呢?

答案 1 :(得分:0)

找到一个解决方案,问题是收到Spring的日期为&#34; YYYY-MM-ddTHH:mm:ss&#34;因此,如果要将其直接发送到数据库,则必须以此格式发送,或者在保留数据的那一刻将其转换为数据库格式。

我没有找到一种改变Spring接收格式的工作方式。我只是在有人进行GET时以更友好的格式接收信息时更改格式。

对于喜欢我的人来说,出于某种随机原因需要将日期作为ID。 谢谢!