Can't deserialize list directly inside rootelement using Jackson XML
I am unable to deserialize a list that is a child directory of the root, I have tried different 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 an 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 ignorant (one property : "Cards"]) in [Source: C: \ Users \ Frank \ Dropbox \ NetbeansProjects \ Cardshifter \ cardhifter-core \ target \ test-classes \ com \ cardshifter \ core \ cardloader \ single-card.xml; line: 3, column: 9] (via reference chain: com.cardshifter.core.cardloader.Cards ["Card"])
source to share
First of all, look at them:
@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 he say "Card" in his class.
Second, after fixing this, here's how I resolved your entire download:
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 method setCard
simply tells Jackson that if he comes across this, he should interpret it as Card
, and then you provide a method that adds it to the array.
source to share