简体   繁体   中英

Deserialize a Jackson/Json object containing a List<Object> where the list type is a property in the object

I'm trying to deserialize a json object that contains a list where the type of the list is a property in the object. Ie

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

A restriction I have is that the beans I want to deserialized into are generated and I can't modify them. I'm pretty sure I need a custom JsonDeserializer deserializer. I put the deserializer on the data type:

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

The deserializer works but the problem is I can't get the table property from the parent object. I'm getting the TableOutput object, and the hash property has the correct value, but the table property is null. I'm just guessing but I think objectMapper is processing the 'data' property before the 'table' property.

Here's my 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 ...

I need to be able to get the table property so I know what kinds of objects to make for the list. Suggestions?

Maybe use a generic value for the object. Can't say for sure this will work in your case, but when using GSON for setting up my JSON objects I set up a generic class so that when I went to import a JSON object I could tell it what kind of object to use in the List. Something like

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

then use it with a reference to the class you want to be in the list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM