对象转换为 Json 字符串并转换回对象失败,缺少 DateTime 元素 Android

Object conversion to Json String and conversion back to object failing with missing DateTime element Android

我正在尝试将对象保存到共享首选项中然后检索。

该对象由当天的单个 DateTime 和最大股票损失的对象列表组成(股票代码为字符串,百分比变化为双精度) .

对象模型是:

public class DayLosersSharedPreference {

    LocalDateTime dateTime;
    List<PercentageChange> percentageChangesList;

    public LocalDateTime getDateTime() {
        return dateTime;
    }

    public void setDateTime(LocalDateTime dateTime) {
        this.dateTime = dateTime;
    }

    public List<PercentageChange> getPercentageChangesList() {
        return percentageChangesList;
    }

    public void setPercentageChangesList(List<PercentageChange> percentageChangesList) {
        this.percentageChangesList = percentageChangesList;
    }
}

单个对象(包含 DateTime 和对象列表)被传递到我的共享首选项 class 进行存储,如下所示:

public class SharedPreferences {

    Context context = MySuperAppApplication.getContext();
    android.content.SharedPreferences sharedPreferences = context.getSharedPreferences(STRINGS.LOSERS_SP(), Context.MODE_PRIVATE);
    Gson gson = new Gson();

    public void storeLosers(DayLosersSharedPreference losers) {

        System.out.println("Object being stored date: " + losers.getDateTime());
        System.out.println("Object being stored array: " + losers.getPercentageChangesList());

        String dailyLosersJson = gson.toJson(losers);

        System.out.println("Object being stored as Json String: " + dailyLosersJson);

        sharedPreferences.edit()
                .putString(STRINGS.DAILY_LOSERS_SP(), dailyLosersJson)
                .apply();
    }
}

println() 的输出显示 Json 字符串转换正常之前的对象:

I/System.out: Object being stored date: 2019-03-18T00:00
I/System.out: Object being stored array: [com.roboticc.alpha.Models.PercentageChange@8bef7ab, com.roboticc.alpha.Models.PercentageChange@207be08, com.roboticc.alpha.Models.PercentageChange@b6289a1, com.roboticc.alpha.Models.PercentageChange@269d7c6, com.roboticc.alpha.Models.PercentageChange@ff36387, com.roboticc.alpha.Models.PercentageChange@45eb2b4, com.roboticc.alpha.Models.PercentageChange@1fd1edd, com.roboticc.alpha.Models.PercentageChange@41baa52, com.roboticc.alpha.Models.PercentageChange@b18b123, com.roboticc.alpha.Models.PercentageChange@38e4620]

但是我将其转换为 Json 字符串的方式存在问题。当我查看转换后的输出时,它丢失了 DateTime 元素:

I/System.out: Object being stored as Json String: {"dateTime":{},"percentageChangesList":[{"percentageChange":-0.15908367801463796,"symbol":"AAL"},{"percentageChange":0.0,"symbol":"AAME"},{"percentageChange":0.19011406844106543,"symbol":"AABA"},{"percentageChange":0.500000000000002,"symbol":"AAOI"},{"percentageChange":0.6455517450070613,"symbol":"AAWW"},{"percentageChange":0.8957770510450668,"symbol":"AAXJ"},{"percentageChange":1.0208467655276197,"symbol":"AAPL"},{"percentageChange":1.081223628691974,"symbol":"ABCB"},{"percentageChange":2.0748867159551576,"symbol":"AAON"},{"percentageChange":4.29524603836531,"symbol":"AAXN"}]}

一旦我从共享首选项中检索到它,可以预见我会在日期时间上得到一个空指针,因为它没有被保存但可以访问百分比更改列表。

我认为我从对象转换为 Json 字符串的方式有问题,我是否必须做一些事情,比如传递模型类型?或者 DateTime 不能以那种格式存储在 Json 中?

感谢您的帮助

编辑:我能够将 DateTime 更改为字符串并在检索后转换回来以修复此问题。我仍然对为什么没有 DateTime 转换就不能直接工作感兴趣。特别是考虑到可以传递整个对象列表。

gson 不知道 LocalDateTime 对象,因此无法解析它。如果您确实希望它直接解析 LocalDateTime 而不必先将其转换为字符串,则必须告诉 gson 如何使用 registerTypeAdaptor 解析 LocalDateTime。

Gson gson = new GsonBuilder().registerTypeAdapter(LocalDateTime.class, new JsonDeserializer<LocalDateTime>() {
    @Override
    public LocalDateTime deserialize(JsonElement json, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
        Instant instant = Instant.ofEpochMilli(json.getAsJsonPrimitive().getAsLong());
        return LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
    }
}).create();

这是较新版本的 GSON 可能能够处理的问题:https://github.com/google/gson/pull/1266/files

我不确定上面的提交是否已经发布到他们的任何版本中,但看起来某些 duture 版本确实能够自动处理这个问题。