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

标签 java android json gson java-time

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

该对象由当天的单个 DateTime 和最大股票跌幅的对象列表组成(股票代码为字符串,百分比变化为 double )。

对象模型是:

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 中吗?

感谢您的帮助

编辑:我能够将日期时间更改为字符串,并在检索后转换回来以解决此问题。我仍然感兴趣为什么在没有日期时间转换的情况下这不能直接工作。特别是考虑到可以传递整个对象列表。

最佳答案

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

关于java - 对象转换为 Json 字符串并转换回对象失败,缺少 DateTime 元素 Android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55236392/

相关文章:

java - 如何从锁屏以编程方式更改亮度

json - Arm 模板中的 copyindex() 错误

json - Node JS : Make a flat json from a tree json

java - 我收到此 "NullPointerException"错误

android - 防止 AutoCompleteTextView 在自己的框中显示结果

java - 返回变量从 fragment 到 fragment

javascript - 如何在html中显示多个json数据

java - 在 AlertDialog 中显示自定义 View

Java 泛型 : compatible service subclass

java - 如何从java中的图像创建mpeg视频