Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
651 views
in Technique[技术] by (71.8m points)

java - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...