简体   繁体   中英

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 . I have list of dates in JSON , and when I try to deserialize it, I get following error:

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) .

My code:
Gson:

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

Field in Java class:
 private List<Date> freeDates;

Part of JSON for that field:
 {"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...
Sorry for repeating question.
Thanks in advance!

UPDATE: Part of code where I call fromJson method. This is my GenericRepository class, all Repository classes extend this class.

 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:

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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