简体   繁体   English

如何在SpringMVC和Hibernate中从JSON响应中获取日期格式响应而不是毫秒

[英]How to get date format response instead of millisecond from json response in springmvc and hibernate

I am doing a sample of rest services using springmvc and hibernate,in which i am getting date response in millisecond format for date datatype,i have used below code by google search,but there is no effect of those code it results same milliseconds format.below is my code used 我正在使用springmvc和hibernate进行其余服务的示例,其中我以毫秒格式获取日期数据类型的日期响应,我在Google搜索中使用了以下代码,但是这些代码不会产生相同的毫秒格式。以下是我使用的代码

controller.java controller.java

/* Getting List of objects in Json format in Spring Restful Services */  
 @RequestMapping(value = "/list", method = RequestMethod.GET)  
 public @ResponseBody  List getDatalist() { 
  List DataList = null;  
  try {  
      DataList = dataServices.getDataEntityList();  
  } catch (Exception e) {  
   e.printStackTrace();  
  }  
  return DataList;  
 }   

DataValueTable.java DataValueTable.java

  @JsonAutoDetect
@Entity  
@Table(name = "DataValueTable")  
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})  
public class DataValueTable  implements Serializable {  

 private static final long serialVersionUID = 1L;  

 @Id  
 @GeneratedValue  
 @Column(name = "ID")  
 private long id;  

 @JsonSerialize(using=JsonDateSerializer.class)
 @Column(name = "Datatype") 
 private Date dataType;  

 @Column(name = "Datacategory")  
 private String dataCategory;  

 @Column(name = "DataValue")  
 private boolean dataValue;
     public Date getDataType() {
    return dataType;
}

public void setDataType(Date dataType) {
    this.dataType = dataType;
}

JsonDateSerializer .java JsonDateSerializer .java

package com.beingjavaguys.model;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.JsonSerializer;
import org.codehaus.jackson.map.SerializerProvider;
import org.springframework.stereotype.Component;
/**
 * Used to serialize Java.util.Date, which is not a common JSON
 * type, so we have to create a custom serialize method;.
 *
 * @author Loiane Groner
 * http://loianegroner.com (English)
 * http://loiane.com (Portuguese)
 */
@Component
public class JsonDateSerializer extends JsonSerializer<Date>{
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("MM-dd-yyyy");
@Override
public void serialize(Date date, JsonGenerator gen, SerializerProvider provider)
throws IOException, JsonProcessingException {
String formattedDate = dateFormat.format(date);
gen.writeString(formattedDate);
}
}

spring-config.xml 春天-config.xml中

 <context:component-scan base-package="com.beingjavaguys.controller" />  
 <mvc:annotation-driven />  

 <bean id="dataSource"  
  class="org.springframework.jdbc.datasource.DriverManagerDataSource"> 
  <property name="driverClassName" value="com.microsoft.sqlserver.jdbc.SQLServerDriver" />  
  <property name="url" value="jdbc:sqlserver://localhost;database=Sample" />  
  <property name="username" value="sdsd" />  
  <property name="password" value="sdsd" /> 
    <property name="hibernate.dialect" value="com.beingjavaguys.model.SqlServerDialectWithNvarchar" /> 
 </bean>  


 <bean id="sessionFactory"  
 class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">  
 <property name="dataSource" ref="dataSource" />  
 <property name="annotatedClasses">  
 <list>  
   <value>com.beingjavaguys.model.Employee</value>   
      <value>com.beingjavaguys.model.DataValueTable</value> 
   </list>  
  </property>  
  <property name="hibernateProperties">  
   <props>  

    <prop key="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</prop>  
    <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>  
   </props>  
  </property>  
 </bean>  


 <bean id="txManager"  
  class="org.springframework.orm.hibernate4.HibernateTransactionManager">  
  <property name="sessionFactory" ref="sessionFactory" />  
 </bean>  

 <bean id="persistenceExceptionTranslationPostProcessor"  
  class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />  

 <bean id="dataDao" class="com.beingjavaguys.dao.DataDaoImpl"></bean>  
 <bean id="dataServices" class="com.beingjavaguys.services.DataServicesImpl"></bean>  
</beans>  

Right now i am getting response as "12312121000".I want it to display in 02-02-2015 format.Any suggestion and answers are welcomed. 目前,我收到的回复为“ 12312121000”。我希望它以2015年2月2日的格式显示。欢迎提出任何建议和答案。

With jackson you can annotate the entity such as 使用杰克逊,您可以注释诸如

@JsonFormat(shape=JsonFormat.Shape.STRING, pattern="yyyy-MM-dd HH:mm:ss.000 ", timezone="UTC")
public Timestamp getDate() {
    return date;
}

This is an example of a test case I used to get back the timestamp in the pattern. 这是我用来获取模式中时间戳的测试用例的示例。

    ObjectMapper mapper = new ObjectMapper();
    JaxbAnnotationModule module = new JaxbAnnotationModule();
    mapper.registerModule(module);      
    mapper.setSerializationInclusion(Include.NON_NULL);
    // Object to JSON - entityBean I want to map to JSON
    String jsonOutput = mapper.writeValueAsString(entityBean);

Note. 注意。 You must assign the annotated JsonFormat to getter method. 您必须将带注释的JsonFormat分配给getter方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM