fromJson raises unparseable date exception
Asked Answered
C

2

2

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?

Castlereagh answered 22/5, 2015 at 13:13 Comment(2)
please post your result hereCelaeno
The result is posted above.. i get it when i put the problematic line in try..catch block - this is the value of the exception.Castlereagh
C
1

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

Castlereagh answered 24/5, 2015 at 22:14 Comment(0)
I
1

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.

Edit

Changed the format from yyyy/MM/dd to yyyy-MM-dd

Idyll answered 22/5, 2015 at 13:42 Comment(1)
Did it in the beginning. but still exception is raised.Castlereagh
C
1

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

Castlereagh answered 24/5, 2015 at 22:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.