fromJson raises unparseable date exception

我的未来我决定 提交于 2019-12-11 03:49:09

问题


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?


回答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




回答2:


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



来源:https://stackoverflow.com/questions/30397671/fromjson-raises-unparseable-date-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!