无法使用Jackson XML直接在rootelement内反序列化列表

时间:2014-10-28 18:14:01

标签: java xml serialization jackson

我无法反序列化作为根元素子目录的列表,我尝试过各种各样的事情。

我的代码:

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:无法识别的字段&#34;卡&#34; (类com.cardshifter.core.cardloader.XmlCardLoader $ Cards),未标记为可忽略(一个已知属性:&#34; Cards&#34;])    在[来源:C:\ Users \ Frank \ Dropbox \ NetbeansProjects \ Cardshifter \ cardshifter-core \ target \ test-classes \ com \ cardshifter \ core \ cardloader \ single-card.xml; line:3,column:9](通过引用链:com.cardshifter.core.cardloader.Cards [&#34; Card&#34;])

1 个答案:

答案 0 :(得分:9)

首先,看看这些:

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

然后看看错误:

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

在您的班级中,&#34; Card&#34; 无处可说。

其次,在解决之后,这就是我如何解决你的整个装载问题:

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,然后提供将其添加到数组的方法。