【问题标题】:Android [retrofit] - unparsable dateAndroid [改造] - 无法解析的日期
【发布时间】:2018-11-07 11:39:48
【问题描述】:

我使用 Retrofit 发送 GET 请求,但遇到以下问题:

io.reactivex.exceptions.OnErrorNotImplementedException: java.text.ParseException: Unparseable date: "2018-05-09"

我的对象模型:

public class Device {
    private int id;
    private int phoneNumber;
    private String connectionName;
    private String deviceName;
    private Date startConnection;
    private Location actualLocation;
    private User owner;

//getters setters and constructor
}

获取:

public void getAllDevicesForCurrentUser(){
        compositeDisposable.add(restAPI.getDevices("Bearer " + TokenHolder.getInstance().getToken())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<List<Device>>() {
                    @Override
                    public void accept(List<Device> devices) throws Exception {
                        initializeDevices(devices);
                    }
                }));
    }

有什么问题?

【问题讨论】:

  • 需要更多代码。你是怎么接电话的?
  • 我在第一篇文章中添加了更多代码。
  • @Bartosz20188 问题在于您尝试解析日期的位置。您的日期格式不正确,因此请分享该部分代码

标签: android json parsing retrofit


【解决方案1】:

您必须在改造初始化中设置日期格式。这是你可以做到的方法

Gson gson = new GsonBuilder()
.setDateFormat("yyyy-MM-dd")
.create();

Retrofit retrofitAdapter = new Retrofit.Builder()
.baseUrl(API_BASE_URL)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();

【讨论】:

  • 谢谢!我有同样的时间问题。Unparseable date: "00:06:00"
  • "00:06:00" - 这是什么日期?
  • 是时间,不是日期。在数据库中,我的日期为 2018-05-09,另一列时间为 00:06:00
  • 您将不得不使用自定义适配器来解析时间,或者像这样简单地使用日期传递时间 .setDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz")
  • 我可以从 JSON 中排除解析日期和时间吗?
【解决方案2】:

好的,我解决这个问题。

我在对象中的所有变量上方添加@Expose,在不需要从 JSON 解析的变量中添加Expose(deserialized = false)

最后,

Gson gson = new GsonBuilder()
                    .excludeFieldsWithoutExposeAnnotation().setPrettyPrinting().create();

【讨论】:

    【解决方案3】:

    现在我明白了

     io.reactivex.exceptions.OnErrorNotImplementedException: java.text.ParseException: Unparseable date: "00:06:00"
    

    我想将时间解析到我的对象 Location actualLocation where

    public class Device {
        private int id;
        private int phoneNumber;
        private String connectionName;
        private String deviceName;
        private Date startConnection;
        private Location actualLocation;
        private User owner;
    
    //getters setters and constructor
    }
    

    和位置:

    public class Location {
        private int id;
        private float gpsLatitude;
        private float gpsLongitude;
        private Date date;
        private Time time;
        private Device device;
    }
    

    【讨论】:

    • 这不是答案,而是对您的问题的补充,您应该更新它以描述新的问题/行为
    猜你喜欢
    • 2017-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-25
    • 2013-04-21
    • 1970-01-01
    相关资源
    最近更新 更多