簡體   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