简体   繁体   English

使用GSON反序列化两种不同的日期格式

[英]deserialize two different date formats with GSON

Im consuming a clients JSON API using googles GSON lib to handle serialisation/deserialization. 我使用谷歌GSON lib消费客户端JSON API来处理序列化/反序列化。 This is proving to be problematic as within the API's json entities there are a number of date formats scattered about the API. 事实证明这是有问题的,因为在API的json实体中,有许多关于API的日期格式。

Some examples of this are as follows... 这方面的一些例子如下......

"2014-02-09" “2014年2月9日”

"15/10/1976" “15/10/1976”

"2014-02-09T07:32:41+00:00" “2014-02-09T07:32:41 + 00:00”

I have no control over the API as it developerd by the client and is already being consumed by other parties. 我无法控制客户开发的API,并且已被其他方消费。 It seems that I can setup GSON to work with a single date format but I cant get it parse the dates on a per field basis. 似乎我可以设置GSON使用单个日期格式,但我不能让它解析每个字段的日期。

I would have expected GOSN to provide an annotation for this but I cant seem to find one. 我原以为GOSN会为此提供一个注释,但我似乎无法找到一个。 Any ideas on ho to set this up anyone? 有什么想法来设置这个人吗?

Since you have multiple Date fields in your POJO, and the incomming JSON has those dates in different formats, you'd need to write a custom deserializer for Date that can handle those formats. 由于POJO中有多个Date字段,并且包含JSON的日期具有不同格式的日期,因此您需要为Date编写一个可以处理这些格式的自定义反序列化器。

class DateDeserializer implements JsonDeserializer<Date>
{
    @Override
    public Date deserialize(JsonElement je, Type type, JsonDeserializationContext jdc) throws JsonParseException
    {
        String myDate = je.getAsString();
        // inspect string using regexes
        // convert string to Date        
        // return Date object
    }

}

You can the register this as a type adapter when creating your Gson instance: 您可以在创建Gson实例时将其注册为类型适配器:

Gson gson = new GsonBuilder()
                .registerTypeAdapter(Date.class, new DateDeserializer())
                .create(); 

You can, of course, also just write a custom deserializer for your POJO and populate everything yourself from the parse tree. 当然,您也可以为POJO编写自定义反序列化器,并从解析树中自行填充所有内容。

Another option would be to simply set them as a String in your POJO, then make the getters for each field convert them to Date . 另一种选择是在POJO中简单地将它们设置为String ,然后使每个字段的getter将它们转换为Date

Outside of that, if you're not completely attached to using Gson, the Jackson JSON parser (by default) uses your POJO's setters during deserializtion which would give you the explicit control over setting each field. 除此之外,如果您没有完全依赖于使用Gson,那么Jackson JSON解析器(默认情况下)会在反序列化期间使用您的POJO设置器,这将使您可以明确控制设置每个字段。

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

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