[英]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 的當前版本來解決此問題的替代方法是:
要在構造 GSON object 時在GSONBuilder
中指定備用DateFormat
:
Gson gson = new GsonBuilder().setDateFormat("yyyy-mm-dd").create();
要指定自定義日期反序列化器,如下所示:
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));
}
}
結束語
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.