繁体   English   中英

使用 Json 数据的 Java 中出现不可解析的日期异常

[英]Unparseable Date Exception in Java using Json Data

我是 java 的新手。 尝试转换日期格式时出现异常:无法解析的日期并且不知道如何解决此问题。 日期的格式为"date":"2021-01-12" 我的实体 class 看起来像这样。

我试图做的是以下内容:

private String id;
private Date date ;       
        
    public Date getDate() {
        return date;
    }
    public void setDate(Date date) {
        this.date = date;
    }

我的生意 Class 是:

String dataoffer = "";
    try (BufferedReader br = new BufferedReader(
        new FileReader("D:\\rates.json"))) {
            String sCurrentLine;
    
            while ((sCurrentLine = br.readLine()) != null) {
                dataoffer += sCurrentLine;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
            
        Gson gsondataoffer = new GsonBuilder().create();
            
        CurrencyEntity wrapperData = gsondataoffer.fromJson(dataoffer, CurrencyEntity.class);
        System.out.println(wrapperData);

有谁知道如何转换示例日期

简短的回答

我用各种版本的 GSON 库(和java.util.Date类)测试了你的问题,结果证明它可以在GSON 2.5中工作。

根据他们的发行说明,他们说:

通过接受多种日期格式改进了日期反序列化

您可以在此处找到完整的发行说明。

因此,解决您的问题的最简单方法是简单地升级您使用的 GSON 库的版本。


长答案

问题是 JSON 中指定的DateFormat无法被 GSON 库识别(在 2.5 之前的版本中)。

通过保留您当前拥有的 GSON 的当前版本来解决此问题的替代方法是:

  1. 要在构造 GSON object 时在GSONBuilder中指定备用DateFormat

    Gson gson = new GsonBuilder().setDateFormat("yyyy-mm-dd").create();

  2. 要指定自定义日期反序列化器,如下所示:

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

指定Date-Deserializer的完整代码如下所示(注意将其移动到单独的 class 中,这将使代码更具可读性并产生更精简的代码库。这里它是内联的,以显示尽可能少的代码,但显示原则并列出所需的进口。):

import java.lang.reflect.Type;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;

public class Driver {
    public static void main(String[] args) {

        JsonDeserializer<Date> dateDeserializer = new JsonDeserializer<Date>() {
            public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
                    throws JsonParseException {
                String date = json.getAsString();

                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-mm-dd");

                try {
                    return formatter.parse(date);
                } catch (ParseException e) {
                    System.err.println("Failed to parse Date due to: " + e.toString());
                    return null;
                }
            }
        };

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

        Entity fromJson = gson.fromJson(JsonData.json, Entity.class); // Entity is the entity class in same package as
                                                                        // Driver; JsonData is holding the JSON string
                                                                        // with the date which you have in a file (also
                                                                        // in same package as Driver)
        System.out.println(gson.toJson(fromJson));
    }
}

结束语

  • 还要记住实现并提供类似的Date-Serializer以具有从 Json 到 Json 的一致映射
  • 在现实世界的应用程序中使用Dates时,您可能需要考虑使用不同的时区来以准确的方式处理日期
  • java.util.Date实际上是 Java 与 Dates 一起使用的旧实现。 From Java 8 and above you might consider to work with the new implementations from the java.time.* package like java.time.LocalDateTime or java.time.LocalDate

暂无
暂无

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

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