我有一个场景,我将Object推送到队列,队列将在另一端读取。
我正在将对象转换为字符串,将字符串转换为字节。将这些字节推送到队列中。
CollectionObject collectionObject = new CollectionObject();
// This can be any Object. Or at least Iam thinking it's Object class.
collectionObject.setName("Sienna");
String customerMessage = objectMapper.writeValueAsString(collectionObject);
byte[] msg = customerMessage.getBytes(StandardCharsets.UTF_8);
另一方面,我以这种方式阅读这个物体。
String messageFromQueue = new String(msg);
objectMapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);
Object genericObject = objectMapper.readValue(messageFromQueue, new TypeReference<Object>(){});
System.out.println("let's see object"+genericObject);
if(genericObject instanceof CollectionObject)
System.out.println("turned out to be collectionObject "+genericObject);
但支票的例子永远不会得到满足。readValue返回LinkedHashMap对象。
任何帮助,感谢
问题
没有任何内容指示要封送到的类:{"name":"Sienna"}
。fasterxml怎么可能猜测它应该封送到哪种类型。
一个解决方案
首先启用默认键入:
objectMapper.enableDefaultTyping();
然后考虑在实际负载周围使用包装器对象:
public class Wrapper {
private Object content;
public Wrapper() {
}
public Wrapper(Object content) {
this.content = content;
}
public Object getContent() {
return content;
}
public void setContent(Object content) {
this.content = content;
}
}
然后写入对象:
String customerMessage = objectMapper.writeValueAsString(new Wrapper(collectionObject));
然后读取对象:
Object genericObject = objectMapper.readValue(messageFromQueue, Wrapper.class).getContent();
在这种情况下,genericObject
将是CollectionObject
,json是{"content":["CollectionObject",{"name":"Sienna"}]}