【问题标题】:Passing date as json object through Spring Hibernate通过 Spring Hibernate 将日期作为 json 对象传递
【发布时间】:2015-06-19 18:29:57
【问题描述】:

我正在使用 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 对象传递的帮助。提前谢谢你。

【问题讨论】:

    标签: java json spring hibernate spring-mvc


    【解决方案1】:

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

    使用杰克逊已经识别的格式("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;
    

    全局配置

    还请注意,您可以通过自定义负责转换的 Jackson 的 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);
      }
    }
    

    您需要在 spring 中注册您的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>
    

    【讨论】:

    • 要不要先把json转成String再设置日期。 hibernate会自动进行这种转换吗?
    • Spring MVC 做到了,而他面临的request syntactically incorrect 的问题仍然没有达到休眠状态,这仅仅意味着转换器不知道如何将匹配属性的json 值转换为Date字段
    • 能否请您详细说明我如何以及在何处提及 json 格式。此外,我尝试将您的建议添加到我的代码中。每当我通过邮递员访问资源时,它仍然会给我同样的错误 400。
    • 你问的很好,因为再看一遍我发现我的回答有误,希望现在能提供更多帮助
    • 它现在工作得很好。除了当我调用 getDetail API 时,我得到的日期格式是 "implementationDate": 1425234600000, "validFrom": 1425234600000, "validUpTo": 1425234600000 .. 所以如果你也能帮助我,这将是一个很大的帮助。提前谢谢你
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多