gpt4 book ai didi

java - 无法使用 Jackson XML 直接在根元素内反序列化列表

转载 作者:数据小太阳 更新时间:2023-10-29 02:01:31 28 4
gpt4 key购买 nike

我无法反序列化作为根元素子目录的列表,我尝试了各种方法。

我的代码:

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

和:

ObjectMapper xmlMapper = new XmlMapper();
Cards cards = xmlMapper.readValue(path.toFile(), Cards.class);

尝试反序列化以下 XML 时:

<Cards>
<Card>
<Name>test</Name>
<Image></Image>
<CardType>test</CardType>
</Card>
</Cards>

它给出错误:

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"])

最佳答案

首先,看看这些:

@JacksonXmlElementWrapper(localName = "Cards")
private List<Card> cards;

然后看报错:

com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "Card" (class com.cardshifter.core.cardloader.XmlCardLoader$Cards)

在你的类里面没有任何地方说“卡片”

其次,在解决这个问题之后,我是这样解决你的整个加载问题的:

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

setCard 方法简单地告诉 Jackson,如果遇到这种情况,它应该将其解释为 Card,然后您提供将其添加到数组的方法。

关于java - 无法使用 Jackson XML 直接在根元素内反序列化列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26615540/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com