ObjectMapper-读/写通用对象

时间:2018-11-16 10:16:18

标签: java fasterxml

我有一种情况,我将“对象推入队列”,这将在另一端读取。

我正在将对象转换为字符串,将字符串转换为字节。将这些字节推送到队列。

lines = gridfile.readlines()
for i,line in enumerate(lines):
    if "width" in line:
        grid_id['width'] = re.sub('[A-z]', '', line).strip()
    if "height" in line:
        grid_id['height'] = re.sub('[A-z]', '', line).strip()
    if "rows" in line:
        idx_rows = i
    if "columns" in line:
        idx_cols = i

width = int(grid_id['width'])
height = int(grid_id['height'])
rows = lines[idx_rows+1:idx_rows+1+height]
cols = lines[idx_cols+1:idx_cols+1+width]

另一方面,我正在以这种方式阅读该对象。

        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);

但是检查实例永远不会满足。 readValue返回我LinkedHashMap对象。

任何帮助, 谢谢

1 个答案:

答案 0 :(得分:0)

问题

没有任何迹象表明该班级要编入:{"name":"Sienna"}。 fastxml怎么可能猜测它应该编组为哪种类型。

一种解决方案

首先启用默认键入:

    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"}]}