反序列化包含List <object>的Jackson / Json对象,其中列表类型是对象中的属性

时间:2018-10-29 19:35:20

标签: java json jackson objectmapper

我正在尝试反序列化包含列表的json对象,其中列表的类型是对象中的属性。即

public class TableOutput 
{
    private String hash;
    private String table;  // contains the object type in data list
    private List<Object> data;
}

我的一个限制是生成了要反序列化为的bean,但是我无法对其进行修改。我很确定我需要一个自定义的JsonDeserializer解串器。我将反序列化器放在了数据类型上:

@JsonDeserialize(contentAs = TableOutputDeserializer.class)
private List<Object> data;

解串器有效,但问题是我无法从父对象获取table属性。我正在获取TableOutput对象,并且hash属性具有正确的值,但是table属性为null。我只是在猜测,但我认为objectMapper在处理'table'属性之前先处理'data'属性。

这是我的JsonDeserializer:

public class TableOutputDeserializer extends JsonDeserializer<Object> {
@Override
public Object deserialize(JsonParser jp, DeserializationContext ctxt)
        throws IOException, JsonProcessingException {
    // Get reference to ObjectCodec
    ObjectCodec codec = jp.getCodec();

    // Parse "object" node into Jackson's tree model
    JsonNode node = codec.readTree(jp);

    // Get the TableOutput object
    TableOutput tableOutput=(TableOutput)jp.getParsingContext().getParent().getCurrentValue();

    // got a valid tableOutput instance. 
    String objectType=tableOutput.getTable(); // objectType is always null!!!

    Iterator<JsonNode> elements = node.elements();
    ... more stuff ...

我需要能够获取table属性,以便知道要为列表创建哪种对象。有建议吗?

1 个答案:

答案 0 :(得分:0)

也许为对象使用一个通用值。不能肯定地说这将在您的情况下起作用,但是当使用GSON设置我的JSON对象时,我设置了一个通用类,以便当我导入JSON对象时,我可以告诉它要使用哪种对象名单。像

public class JsonClass <T> {
  private List<T> unknownItems;
}

然后将其与要在列表中显示的班级一起使用。

相关问题