首页 > 解决方案 > 对象转换为 Json 字符串并转换回对象失败,缺少 DateTime 元素 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 和对象列表)被传递给我的共享首选项类进行存储,如下所示:

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 转换,这不能直接工作。特别是考虑到可以传递整个对象列表。

标签: javaandroidjsongsonjava-time

解决方案


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 版本将能够自动处理此问题。


推荐阅读