Search code examples
javaandroiddategsonunparseable

fromJson raises unparseable date exception


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?


Solution

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