java jackson在序列化后保留类型信息,如果类型为Object的变量 [英] java jackson keep type information after serialize if variable of type Object
问题描述
ClassA
public class ClassA {
private String id;
private Object rawData;
}
B 类
public class ClassB {
private String name;
}
ClassC
public class ClassC {
String address;
}
主类
public class MainExample {
public static void main( String[] args ) throws IOException {
ObjectMapper mapper = new ObjectMapper( );
ClassB classB = new ClassB();
//ClassC classC = new ClassC();
ClassA classA = new ClassA();
classA.setRawData( classB );
//classA.setRawData( classC );
if (classA.getRawData() instanceof ClassB) {
System.out.println("true ");
} else {
System.out.println("false");
}
String classAString = mapper.writeValueAsString( classA );
ClassA a = mapper.readValue( classAString, ClassA.class );
if (a.getRawData() instanceof ClassB) {
System.out.println("true ");
} else {
System.out.println("false");
}
}
}
为什么第一个 if-else 打印 "TRUE" 和第二个 if-else 打印 "false"??
why first if-else printing "TRUE" and second if-else printing "false"??
如何查看 rawData 的类型?
How can I check the type of rawData?
推荐答案
mapper.writeValueAsString(classA)
会将实例序列化为类似于 {"rawData":{}}代码>.
mapper.writeValueAsString(classA)
will serialise the instance into something similar to {"rawData":{}}
.
反序列化 {}
时,默认映射器会失败,因为它将 {}
视为不可序列化的类型.如果您之前已将 SerializationFeature.FAIL_ON_EMPTY_BEANS
配置为 false
,您将创建一个空的 Object
.
While deserialising {}
the default mapper would fail, because it treats {}
as a non-serializable type. If you've configured SerializationFeature.FAIL_ON_EMPTY_BEANS
to false
before, you will have an empty Object
created.
您可能希望使用 mapper.enableDefaultTyping();
在 JSON 中包含类型信息,从而反序列化为正确的类型.
You might want to use mapper.enableDefaultTyping();
to include type information in JSON, and thereby deserialize into the correct types.
注意:如果传入的内容来自不受信任的来源,则使用默认类型可能存在潜在的安全风险,建议不要这样做,或者,如果启用,使用 setDefaultTyping
传递一个自定义 TypeResolverBuilder
实现,用于将要使用的合法类型列入白名单.
NOTE: use of Default Typing can be a potential security risk if incoming content comes from untrusted sources, and it is recommended that this is either not done, or, if enabled, use
setDefaultTyping
passing a customTypeResolverBuilder
implementation that white-lists legal types to use.
这篇关于java jackson在序列化后保留类型信息,如果类型为Object的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!