java.util.concurrent.ExecutionException: com.google.gson.JsonSyntaxException: 2020-01-15 15:13:42.0

java.util.concurrent.ExecutionException: com.google.gson.JsonSyntaxException: 2020-01-15 15:13:42.0

我使用 Gson 发送数据并使用 Gson 库将 JSON 转换为对象。

JSON 数据 -

{
   "map":{
      "date":"2020-01-15 15:13:42.0",
      "botType":1,
      "botName":"ds",
      "id":62,
      "userId":1,
      "accountKey":"dcab171a-b6cc-4583-b5fc-3e996100725a",
      "status":0
   }
}

数据转换 class 是:

public class DateConverter {
    @TypeConverter
    public static Date toDate(Long timestamp) {
        return timestamp == null ? null : new Date(timestamp);
    }

    @TypeConverter
    public static Long toTimestamp(Date date) {
        return date == null ? null : date.getTime();
    }
}

我在 android 中从服务器获取数据时遇到问题,出现这样的错误:

01-27 15:47:00.506 2070-2070/xxx.xx.xxxxx.android W/System.err: java.util.concurrent.ExecutionException: com.google.gson.JsonSyntaxException: 2020-01-15 15:13:42.0
01-27 15:47:00.506 2070-2070/xxx.xx.xxxxx.android W/System.err:     at java.util.concurrent.FutureTask.report(FutureTask.java:93)
01-27 15:47:00.506 2070-2070/xxx.xx.xxxxx.android W/System.err:     at java.util.concurrent.FutureTask.get(FutureTask.java:163)
01-27 15:47:00.506 2070-2070/xxx.xx.xxxxx.android W/System.err:     at android.os.AsyncTask.get(AsyncTask.java:483)

发件人代码:

objectOutputStream = new ObjectOutputStream(response.getOutputStream());
                    objectOutputStream.writeObject(new Gson().toJson((JSONObject) messageForClient.getT()));

创建 Gson 实例时,定义日期格式。

例如:

Gson gson = new GsonBuilder()
   .setDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz").create();

尝试修改字符串格式以匹配您的日期语法。

使用这个:

new GsonBuilder().setDateFormat("yyyy-MM-DD HH:mm:ss").create().fromJson(string , YourObject.class);

您的格式是:"yyyy-MM-DD HH:mm:ss"