Gson日期类型例外:我如何修复异常?

时间:2011-11-16 16:33:47

标签: java android json gson

我正在使用Gson将json转换为Java类... firstLogin的类型是java.util.Date

public static void main(String[] args) {

     String lineString="{\"email\":\"sadas\",\"faith\":121,\"qq\":211,\"account\":2412,\"userName\":\"asda\",\"firstLogin\":1321362590000,\"uid\":1}";
     Gson gson=new Gson();
User user=gson.fromJson(lineString, User.class);
    System.out.println(user.getFirstLogin());
}

例外:

Exception in thread "main" com.google.gson.JsonSyntaxException: 1321362590000
    at com.google.gson.internal.bind.DateTypeAdapter.deserializeToDate(DateTypeAdapter.java:78)
    at com.google.gson.internal.bind.DateTypeAdapter.read(DateTypeAdapter.java:63)
    at com.google.gson.internal.bind.DateTypeAdapter.read(DateTypeAdapter.java:38)
    at com.google.gson.internal.bind.TypeAdapters$19$1.read(TypeAdapters.java:462)
    at com.google.gson.internal.bind.TypeAdapters$19$1.read(TypeAdapters.java:466)
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.read(ReflectiveTypeAdapterFactory.java:86)
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:170)
    at com.google.gson.Gson.fromJson(Gson.java:720)
    at com.google.gson.Gson.fromJson(Gson.java:686)
    at com.google.gson.Gson.fromJson(Gson.java:636)
    at com.google.gson.Gson.fromJson(Gson.java:608)
    at gsontest.GsonTest.main(GsonTest.java:22)
Caused by: java.text.ParseException: Unparseable date: "1321362590000"
    at java.text.DateFormat.parse(DateFormat.java:357)
    at com.google.gson.internal.bind.DateTypeAdapter.deserializeToDate(DateTypeAdapter.java:76)
    ... 11 more
Java Result: 1

如何解决问题...谢谢

1 个答案:

答案 0 :(得分:1)

firstLogin在json中有一个long类型,因此请将其作为long变量从JSON获取,并使用Date构造函数创建一个新的Date(long milliseconds)