Java 配置 Jackson 解析多种日期格式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24912992/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 15:35:04  来源:igfitidea点击:

Configure Hymanson to parse multiple date formats

javaandroidjsonHymanson

提问by Kurian Vithayathil

I am working on a project where the date formats returned in JSON payloads aren't consistent (that's another issue all together). The project I'm working on uses Hymanson to parse the JSON responses. Right now I've written a few de/serializers to handle it but it's not elegant.

我正在处理一个项目,其中 JSON 有效负载中返回的日期格式不一致(这是另一个问题)。我正在从事的项目使用 Hymanson 来解析 JSON 响应。现在我已经编写了一些反序列化程序来处理它,但它并不优雅。

I want to know whether there's a way to configure Hymanson with a set of possible date formats to parse for a particular response rather than writing several separate deserializers for each format. Similar to how GSON handles the problem in this question

我想知道是否有一种方法可以使用一组可能的日期格式来配置 Hymanson 来解析特定的响应,而不是为每种格式编写几个单独的反序列化器。类似于GSON如何处理这个问题中的问题

回答by Keno

In the meanwhile, an annotation became available for a much simpler solution:

与此同时,一个注释可用于更简单的解决方案:

public class DateStuff {
    @JsonFormat(shape=JsonFormat.Shape.STRING, pattern="yyyy-MM-dd,HH:00", timezone="CET")
    public Date creationTime;
}

回答by rouble

Here is a Hymanson Multi Date Format Serializer.

这是 Hymanson Multi Date Format Serializer。

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;

import com.fasterxml.Hymanson.core.JsonParseException;
import com.fasterxml.Hymanson.core.JsonParser;
import com.fasterxml.Hymanson.core.JsonProcessingException;
import com.fasterxml.Hymanson.databind.DeserializationContext;
import com.fasterxml.Hymanson.databind.JsonNode;
import com.fasterxml.Hymanson.databind.deser.std.StdDeserializer;

public class MultiDateDeserializer extends StdDeserializer<Date> {
    private static final long serialVersionUID = 1L;

    private static final String[] DATE_FORMATS = new String[] {
        "MMM dd, yyyy HH:mm:ss",
        "MMM dd, yyyy"
    };

    public MultiDateDeserializer() {
        this(null);
    }

    public MultiDateDeserializer(Class<?> vc) {
        super(vc);
    }

    @Override
    public Date deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        JsonNode node = jp.getCodec().readTree(jp);
        final String date = node.textValue();

        for (String DATE_FORMAT : DATE_FORMATS) {
            try {
                return new SimpleDateFormat(DATE_FORMAT).parse(date);
            } catch (ParseException e) {
            }
        }
        throw new JsonParseException(jp, "Unparseable date: \"" + date + "\". Supported formats: " + Arrays.toString(DATE_FORMATS));
    }
}

You can use this simply by annotating a field as follows:

您可以简单地通过如下注释字段来使用它:

@JsonProperty("date") @JsonDeserialize(using = MultiDateDeserializer.class) final Date date,