Josh Wilson Josh Wilson - 1 year ago 69
JSON Question

Jackson list deserialization. nested Lists

I'm working on creating an API that has nested lists. Jackson seems like a great tool to create objects, but I can't quite figure out how to nest a list, and I'm wondering if its possible.

My object looks like this.

public class Order {
public String name;
public List<Item> items;
}


I'm hoping there is a way to map it to json that looks something like:

{
name : "A name"
items : {
elements : [{
price : 30
}]
}
}


We want to be able to do this so we can add properties to lists.

Answer Source

You can write custom deserializer for List<Item> items. See below example:

class ItemsJsonDeserializer extends JsonDeserializer<List<Item>> {

    @Override
    public List<Item> deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        InnerItems innerItems = jp.readValueAs(InnerItems.class);

        return innerItems.elements;
    }

    private static class InnerItems {
        public List<Item> elements;
    }
}

Now, you have to inform Jackson to use it for your property. You can do this in this way:

public class Order {
  public String name;
  @JsonDeserialize(using = ItemsJsonDeserializer.class)
  public List<Item> items;
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download