Reputation: 193
I develop android app which have client-server and DB.
I use gson to parse the objects between the server and the client.
My type of the date is java.sql.date
when I run this code (Message is an object which I created...):
public ArrayList<Message> getMessagesByKehilaName(String kehilaName) throws Exception {
String result = GET(URL + "getMessagesByKehilaName?kehilaName=" + kehilaName);
Gson gson = new Gson();
ArrayList<Message> am = new ArrayList<Message>(Arrays.asList(gson.fromJson(result, Message[].class)));
return am;
}
I get this exception:
com.google.gson.JsonSyntaxException: java.text.ParseException: Unparseable date: "2011-11-05" (at offset 0)
the value on my DB is indeed 2011-11-05
and the type of my Message Date is also java.sql.date
.
why do I have this exception?
Upvotes: 2
Views: 1722
Reputation: 193
I changed the registerTypeAdapter to be java.util.date and now it works:
SqlDateTypeAdapter sqlAdapter = new SqlDateTypeAdapter();
Gson gson = new GsonBuilder()
.registerTypeAdapter(java.util.Date.class, sqlAdapter )
.setDateFormat("yyyy-MM-dd")
.create();
I am not sure why it works. my type is sql.Date, but this is works..
Upvotes: 1
Reputation: 3679
Gson default Date adapter and date format are different. You need to register the SQL Date type adapter, and also set the expected date format before deserialze the JSON.
SqlDateTypeAdapter sqlAdapter = new SqlDateTypeAdapter();
Gson gson = new GsonBuilder()
.registerTypeAdapter(java.sql.Date.class, sqlAdapter )
.setDateFormat("yyyy-MM-dd")
.create();
Now use this gson
object to parse the data.
Changed the format from yyyy/MM/dd
to yyyy-MM-dd
Upvotes: 1