我有一个类似于下面的类
public class MyClass {
private String val1;
private String val2;
private Map<String,Object> context;
// Appropriate accessors removed for brevity.
...
}
I'm looking to be able to make the round trip with Jackson from object to JSON and back. I can serialize the object above fine and receive the following output:
{
"val1": "foo",
"val2": "bar",
"context": {
"key1": "enumValue1",
"key2": "stringValue1",
"key3": 3.0
}
}
我遇到的问题是,因为序列化映射中的值没有任何类型信息,所以它们没有正确地反序列化.例如,在上面的示例中,枚举值1应该反序列化为枚举值,而不是反序列化为字符串.我已经看到了将什么类型建立在各种事物上的示例,但是在我的场景中,我不知道类型是什么(它们将是用户生成的对象,我事先不知道),所以我需要能够用键值对序列化类型信息.我怎么才能和杰克逊一起做到这一点呢?
作为记录,我使用的是杰克逊2.4.2版.我用来测试往返的代码如下:
@Test
@SuppressWarnings("unchecked")
public void testJsonSerialization() throws Exception {
// Get test object to serialize
T serializationValue = getSerializationValue();
// Serialize test object
String json = mapper.writeValueAsString(serializationValue);
// Test that object was serialized as expected
assertJson(json);
// Deserialize to complete round trip
T roundTrip = (T) mapper.readValue(json, serializationValue.getClass());
// Validate that the deserialized object matches the original one
assertObject(roundTrip);
}
由于这是一个基于Spring的项目,映射器的创建过程如下:
@Configuration
public static class SerializationConfiguration {
@Bean
public ObjectMapper mapper() {
Map<Class<?>, Class<?>> mixins = new HashMap<Class<?>, Class<?>>();
// Add unrelated MixIns
..
return new Jackson2ObjectMapperBuilder()
.featuresToDisable(SerializationFeature.WRITE_DATE_KEYS_AS_TIMESTAMPS)
.dateFormat(new ISO8601DateFormatWithMilliSeconds())
.mixIns(mixins)
.build();
}
}