fromJson引发了不可解析的日期异常 [英] fromJson raises unparseable date exception

查看:1202
本文介绍了fromJson引发了不可解析的日期异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开发了具有客户端服务器和数据库的android应用程序。



我使用gson来解析服务器和客户端之间的对象。
$ b

我的日期类型是j ava.sql.date



我运行这段代码(Message是一个我创建的对象):

  public ArrayList< Message> getMessagesByKehilaName(String kehilaName)抛出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)));
回报上午;
}

我得到这个异常:


com.google.gson.JsonSyntaxException:java.text.ParseException:无法解析的日期:
2011-11-05(在偏移量0处)


我的数据库的值确实是 2011-11-05 ,我的消息日期的类型是还有 java.sql.date



为什么我有这个异常?

解决方案

我将registerTypeAdapter更改为java.util.date,现在它工作:

  SqlDateTypeAdapter sqlAdapter = new SqlDateTypeAdapter(); 
Gson gson = new GsonBuilder()
.registerTypeAdapter(java.util.Date.class,sqlAdapter)
.setDateFormat(yyyy-MM-dd)
.create() );

我不确定它为什么起作用。我的类型是sql.Date,但这是工程..


I develope 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?

解决方案

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

这篇关于fromJson引发了不可解析的日期异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆