将JSON的嵌套字段转换为java对象

时间:2016-06-25 17:36:09

标签: java json elasticsearch

以下是我的班级

class Feed {
    Long id;
    String title;
    String text;
    Short type;
    Object object;
}

Feed.object可以是基于Feed.type的任何类型。当我将班级文档上传到elasticsearch时,每件事情都可以正常工作,但是,当提取文档时,org.codehaus.jackson.map.ObjectMapper会转换Feed.object中的LinkedHashMap。有没有办法获得实际的对象?我得到的JSON字符串是Feed。

以下是转换:

Feed feed = mapper.readValue(response.getHits().getHits()[0].getSourceAsString(), Feed.class);

1 个答案:

答案 0 :(得分:1)

您可以根据@JsonTypeInfo课程中class的值,使用object来指明type Feed的内容。例如,

class Feed {
    Long id;
    String title;
    String text;
    Short type;
    @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.EXTERNAL_POPERTY, propery = "type")
    @JsonSubTypes({
        @JsonSubTypes.Type(value = Foo.class, name = "1"),
        @JsonSubTypes.Type(value = Bar.class, name = "2")
    })
    Object object;
}
相关问题