简体   繁体   English

由 ParseException 引起的 Java Gson JsonSyntaxException:无法解析的日期

[英]Java Gson JsonSyntaxException caused by ParseException: Unparsable date

I know there is a lot of questions related to this problem on StackOverflow ( I have tried a lot of solutions for them ), but I have been trying for hours to fix this problem and I always get the same error .我知道在 StackOverflow 上很多与这个问题相关的问题我已经为他们尝试了很多解决方案),但我已经尝试了几个小时来解决这个问题,但我总是遇到同样的错误 I have list of dates in JSON , and when I try to deserialize it, I get following error:在 JSON 中有日期列表,当我尝试反序列化它时,出现以下错误:

com.google.gson.JsonSyntaxException: 2020-08-30
Caused by: java.text.ParseException: Unparseable date: "2020-08-30" at java.base/java.text.DateFormat.parse(DateFormat.java:396) at com.google.gson.internal.bind.DateTypeAdapter.deserializeToDate(DateTypeAdapter.java:79) . Caused by: java.text.ParseException: Unparseable date: "2020-08-30" at java.base/java.text.DateFormat.parse(DateFormat.java:396) at com.google.gson.internal.bind.DateTypeAdapter.deserializeToDate(DateTypeAdapter.java:79)

My code:我的代码:
Gson:格森:

private static Gson g = new GsonBuilder()
            .setDateFormat("yyyy-MM-dd")
            .setPrettyPrinting()
            .serializeNulls()
            .create();

Field in Java class: Java 类中的字段:
 private List<Date> freeDates;

Part of JSON for that field: 该字段的部分 JSON:
 {"freeDates": ["2020-08-30", "2020-08-31", "2020-09-01", "2020-09-02"]}

I have also tried other date formats, like ISO-8601 standard, but the result is always the same...我也尝试过其他日期格式,比如 ISO-8601 标准,但结果总是一样的......
Sorry for repeating question.抱歉重复提问。
Thanks in advance!提前致谢!

UPDATE: Part of code where I call fromJson method.更新:我调用fromJson方法的部分代码。 This is my GenericRepository class, all Repository classes extend this class.这是我的 GenericRepository 类,所有 Repository 类都扩展了这个类。

 public List<T> getAllEntities(String fileName){ BufferedReader br = null; List<T> entities = new ArrayList<T>(); try { br = new BufferedReader(new FileReader(fileName)); String line; StringBuilder fileContent = new StringBuilder(); while((line = br.readLine()) != null) { fileContent.append(line); if(line.trim().equals("END")) { fileContent.delete(fileContent.length() - 4, fileContent.length()); T entity = g.fromJson(fileContent.toString(), type); entities.add(entity); fileContent.setLength(0); }else fileContent.append("\\n"); } return entities; }

Your Json string has to have curly braces:你的 Json 字符串必须有花括号:

String json = "{\"freeDates\": [\"2020-08-30\", \"2020-08-31\", \"2020-09-01\", \"2020-09-02\"]}";
Object converted = g.fromJson(json, Object.class);
System.out.println(converted);

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

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