通过Spring Hibernate将日期作为json对象传递

时间:2015-04-14 08:20:07

标签: java json spring hibernate spring-mvc

我正在使用Spring Hibernate框架。我在将日期作为json对象传递时遇到问题。每当我尝试插入一个对象时,它会显示错误400,请求语法错误。

我的控制器类

    @RequestMapping(value="/hospital", method= RequestMethod.POST,
consumes=MediaType.APPLICATION_JSON_VALUE,produces=MediaType.APPLICATION_JSON_VALUE)

public @ResponseBody Status addHospitalInfo(@RequestBody HospitalInformation hospitalInformation){   

try{
    if(hospitalService.addHospitalInfo(hospitalInformation)){

        return new Status(1,"Success");

    }else{
        return new Status(0,"Failed");
    }

}catch(Exception e){
    e.printStackTrace();
    return new Status(0,e.getMessage());
}   
}

我的域类是

private Integer hospitalId;
private String shortName;
private String name;
private Integer packageId;
private Date implementationDate;
private Date validFrom;
private Date validUpTo;
public enum SubscriptionType{Free,Complimentary,Paid}
private Integer totalUsers;
private Package packages;

public enum Status{Active,Inactive}

private SubscriptionType subscriptionType;
private Status status;
//normal getters and setters for other fields

@Column(name = "implementation_date",
            nullable = false)
    public Date getImplementationDate() {
        return implementationDate;
    }
    public void setImplementationDate(Date implementationDate)
    {
        this.implementationDate = implementationDate;
            }

    @Column(name = "valid_from",
            nullable = false)
    public Date getValidFrom() {
        return validFrom;
    }
    public void setValidFrom(Date validFrom) 
    {
        this.validFrom =validFrom;
    }


    @Column(name = "valid_upto",
            nullable = false)
    public Date getValidUpTo() {
        return validUpTo;
    }
    public void setValidUpTo(Date validUpTo) 
    {
        this.validUpTo =validUpTo;
    }

我的道是

@Transactional
public boolean addHospitalInfo(HospitalInformation hospitalInformation)
        throws Exception {
    Session session=sessionFactory.openSession();
    Transaction tx=session.beginTransaction();
    if(findByPackageId(hospitalInformation.getPackageId())== null){
        return false;
    }
    else{
        session.save(hospitalInformation);
        tx.commit();
        session.close();
        return true;
    }

}

@Transactional
public Package findByPackageId(Integer packageId) throws Exception {
    Session session=sessionFactory.openSession();
    Transaction tx= session.beginTransaction();

    List<Package> package1= new ArrayList<Package>();
    package1=session
            .createQuery("from Package where packageId=?")
            .setParameter(0, packageId)
            .list();
     if (package1.size() > 0) {
         return package1.get(0);
     } else {
         return null;
     }  
}

我的服务类只是将对象保存到数据库中。所以我需要有关如何将日期作为json对象传递的帮助。谢谢你提前。

1 个答案:

答案 0 :(得分:0)

要解决您的问题,您可以执行以下两项操作之一:

使用杰克逊已经识别的格式("yyyy-MM-dd'T'HH:mm:ss.SSSZ", "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", "EEE, dd MMM yyyy HH:mm:ss zzz", "yyyy-MM-dd")

编写自定义反序列化程序,例如yyyyMMdd

public class YourDateDeserializer extends JsonDeserializer<Date> {
    @Override
    public Date deserialize(JsonParser jp, DeserializationContext ctxt)
            throws IOException, JsonProcessingException {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
        String date = jp.getText();

        try {
            return format.parse(date);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }
}

并注明您的日期字段,如

@JsonDeserialize(using = YourDateDeserializer.class)
private Date implementationDate;
@JsonDeserialize(using = YourDateDeserializer.class)
private Date validFrom;
@JsonDeserialize(using = YourDateDeserializer.class)
private Date validUpTo;

<强>序列化

要在JSON响应中按照您希望的方式打印日期,您可以编写自定义JSON序列化程序并使用它注释文件,因此yyyyMMdd类似于

public class YourDateSerializer extends JsonSerializer<Date> {

    @Override
    public void serialize(Date value, JsonGenerator jgen,
        SerializerProvider provider) throws IOException,JsonProcessingException {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
        jgen.writeString(format.format(value));
    }

    @Override
    public Class<Date> handledType() {
        return Date.class;
    }
}

而不是注释你的领域,例如

@JsonDeserialize(using = YourDateSerializer.class)
@JsonDeserialize(using = YourDateDeserializer.class)
private Date implementationDate;

全局配置

另请注意,您可以将自定义序列化程序配置为全局生效,方法是自定义负责转换的杰克逊ObjectMapper。像

这样的东西
@Component
public class CustomObjectMapper extends ObjectMapper {
    public CustomObjectMapper() {
        SimpleModule module = new SimpleModule("JsonDateModule", new Version(2, 0, 0, null, null, null));
        module.addSerializer(Date.class, new YourDateSerializer());
        module.addDeserializer(Date.class, new YourDateDeserializer());
        registerModule(module);
  }
}

您需要在春季注册CustomObjectMapper。如果你正在使用XML配置,那就像

    <mvc:annotation-driven>
        <mvc:message-converters register-defaults="true">
            <bean
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                <property name="objectMapper">
                    <bean class="your.package.CustomObjectMapper"/>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>