用Gson作對象和Json字符串相互轉換很方便,但要把包含java.util.Date類型屬性的對象轉換成Json字符串,以下面的代碼:java
Gson gson = new Gson(); String _p = "{'name':'Json','age':'0','birthday':'2016-01-16'}"; Person person = gson.fromJson(_p, Person.class);
有時候會拋以下異常:json
com.google.gson.JsonSyntaxException: 2016-01-16 at com.google.gson.internal.bind.DateTypeAdapter.deserializeToDate(DateTypeAdapter.java:81) at com.google.gson.internal.bind.DateTypeAdapter.read(DateTypeAdapter.java:66) at com.google.gson.internal.bind.DateTypeAdapter.read(DateTypeAdapter.java:41) at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.read(ReflectiveTypeAdapterFactory.java:103) at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:196) at com.google.gson.Gson.fromJson(Gson.java:810) at com.google.gson.Gson.fromJson(Gson.java:775) at com.google.gson.Gson.fromJson(Gson.java:724) at com.google.gson.Gson.fromJson(Gson.java:696)
緣由是Gson會默認會先按本地的日期格式來格式化日期,若是不成功,則再按照英文日期格式格式化日期,若是不成功則用ISO8601Utils格式化日期,若是再不成功就拋出上述異常,Gson處理日期屬性的相關代碼以下:ui
private synchronized Date deserializeToDate(String json) { try { return localFormat.parse(json); } catch (ParseException ignored) {} try { return enUsFormat.parse(json); } catch (ParseException ignored) {} try { return ISO8601Utils.parse(json, new ParsePosition(0)); } catch (ParseException e) { throw new JsonSyntaxException(json, e); } }
因此建立Gson時須要制定日期轉換格式:google
Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
而後就沒問題了
code