简体   繁体   English

HashMap的序列化和反序列化<MyObject, List<Integer> 与杰克逊

[英]Serialization and deserialization of HashMap<MyObject, List<Integer> with Jackson

I am currently working on a small android app that needs to be able to save/restore a range of settings via serialization/deserialization using the Jackson lib.我目前正在开发一个小型 android 应用程序,它需要能够使用 Jackson 库通过序列化/反序列化来保存/恢复一系列设置。 For most parts it works really well and I can serialize my objects and restore them again.对于大多数部分,它工作得非常好,我可以序列化我的对象并再次恢复它们。 Now I need to serialize/deserialize private member with the type:现在我需要使用以下类型序列化/反序列化私有成员:

HashMap<Model, List<Integer>>

Model being one of my own objects containing a bunch of simple values + getter/setter methods.模型是我自己的对象之一,包含一堆简单的值 + getter/setter 方法。 And this is where I run into problems.这就是我遇到问题的地方。 It starts throwing the following error at me:它开始向我抛出以下错误:

DataAccess: Cannot find a (Map) Key deserializer for type [simple type, class com.schulz.toolie.Models.Model] at [Source: (String)"{"; line: 1, column: 1]

I have tried setting annotations like @JsonAnyGetter and @JsonAnySetter on the getter/setter methods along with the @JsonProperty("subscribe") on both the getter, setter and variable.我尝试在 getter/setter 方法上设置 @JsonAnyGetter 和 @JsonAnySetter 等注释,以及在 getter、setter 和变量上设置 @JsonProperty("subscribe") 。

Is there any way to get around this?有没有办法解决这个问题? preferably without writing custom serialization/deserialization methods as I will get quite a few of these.最好不要编写自定义序列化/反序列化方法,因为我会得到很多这样的方法。

Your problem is that Jackson has a standard for converting a Map to JSON.您的问题是 Jackson 有一个将 Map 转换为 JSON 的标准。 The keys of the map are used as the property names in the results JSON.映射的键用作结果 JSON 中的属性名称。

Map<String, Double> groceryPrices = new HashMap<>();
groceryPrices.put("apple", 0.25);
groceryPrices.put("orange", 0.30);

This naturally translates to a JSON object:这自然会转换为 JSON 对象:

{
  "apple": 0.25,
  "orange": 0.30
}

The problem is you are using a complex object to represent a key.问题是您正在使用一个复杂的对象来表示一个键。 There is no simple method for serializing and deserializing your complex object to/from a String.没有简单的方法可以将复杂对象序列化和反序列化到/从字符串。

If you don't want to write custom serialization, I suggest you change your data structure.如果你不想写自定义序列化,我建议你改变你的数据结构。 Your current structure ties together a model with it's Integers.您当前的结构将模型与其整数联系在一起。 You could fold the list of Integers into the Model object itself:您可以将整数列表折叠到模型对象本身中:

Map<String, Model> models; // This could map modelId -> Model which now contains the integers

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM