I am unable to deserialize a list that is directory a child of the root element, I have tried various kinds of things.
My code:
private static class Cards {
@JacksonXmlElementWrapper(localName = "Cards")
private List<Card> cards;
public List<Card> getCards() {
return new ArrayList<>(cards);
}
}
private static class Card {
@JsonProperty("Name")
private String name;
@JsonProperty("Image")
private String image;
@JsonProperty("CardType")
private String cardType;
private final Map<String, Integer> resources = new HashMap<>();
private boolean duplicateResources = false;
private final List<String> duplicateResourceNames = new ArrayList<>();
@JsonAnySetter
private void addResource(final String name, final Object value) {
if (resources.containsKey(name)) {
duplicateResources = true;
duplicateResourceNames.add(name);
}
resources.put(name, Integer.parseInt(value.toString()));
}
public String getName() {
return name;
}
public String getImage() {
return image;
}
public String getCardType() {
return cardType;
}
@JsonAnyGetter
public Map<String, Integer> getResources() {
if (duplicateResources) {
throw new UncheckedCardLoadingException("Resources " + duplicateResourceNames + " have duplicate entries");
}
return new HashMap<>(resources);
}
}
And:
ObjectMapper xmlMapper = new XmlMapper();
Cards cards = xmlMapper.readValue(path.toFile(), Cards.class);
When trying to deserialize the following XML:
<Cards>
<Card>
<Name>test</Name>
<Image></Image>
<CardType>test</CardType>
</Card>
</Cards>
It gives as error:
com.cardshifter.core.cardloader.CardLoadingException: com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "Card" (class com.cardshifter.core.cardloader.XmlCardLoader$Cards), not marked as ignorable (one known property: "Cards"]) at [Source: C:\Users\Frank\Dropbox\NetbeansProjects\Cardshifter\cardshifter-core\target\test-classes\com\cardshifter\core\cardloader\single-card.xml; line: 3, column: 9] (through reference chain: com.cardshifter.core.cardloader.Cards["Card"])
First of all, look at these:
@JacksonXmlElementWrapper(localName = "Cards")
private List<Card> cards;
And then look at the error:
com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "Card" (class com.cardshifter.core.cardloader.XmlCardLoader$Cards)
Nowhere does it say "Card" in your class.
Secondly, after fixing that, here's how I solved your entire loading:
private static class Cards {
@JacksonXmlElementWrapper(localName = "Card")
@JsonProperty("Card")
private List<Card> card = new ArrayList<>();
@JsonSetter
public void setCard(Card card) {
this.card.add(card);
}
}
The setCard
method simply tells Jackson that if it encounters this, it should interpret it as a Card
, and then you provide the method that adds it to the array.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With