开发者

JaxB UNMarshalling Problem

I tried to run the same example in the following thread:

JAXB Annotations - Mapping interfaces and @XmlElementWrapper

but I am receiving the following exception:

unexpected element (uri:"", local:"dog"). Expec开发者_运维知识库ted elements are <{strange question mark symbol}>catchAll>

...

Any idea why I am getting this exception ?


I managed to run the example, But after using XmlElements tag with java.uill.List Here is the code:

@XmlRootElement class Zoo {

@XmlElements({
        @XmlElement(name = "Dog" , type = Dog.class),
        @XmlElement(name = "Cat" , type = Cat.class)
})
private List<Animal> animals;

public static void main(String[] args) throws Exception {
    Zoo zoo = new Zoo();
    zoo.animals = new ArrayList<Animal>();

    Dog doggy = new Dog();
    doggy.setDogProp("Doggy");

    Cat catty = new Cat();
    catty.setCatProp("Catty");

    zoo.animals.add(doggy);
    zoo.animals.add(catty);

    JAXBContext jc = JAXBContext.newInstance(Zoo.class, Dog.class, Cat.class);
    Marshaller marshaller = jc.createMarshaller();

    ByteArrayOutputStream os = new ByteArrayOutputStream();
    marshaller.marshal(zoo, os);

    System.out.println(os.toString());

    Unmarshaller unmarshaller = jc.createUnmarshaller();

    unmarshaller.setEventHandler(new javax.xml.bind.helpers.DefaultValidationEventHandler());

    Zoo unmarshalledZoo = (Zoo) unmarshaller.unmarshal(new ByteArrayInputStream(os.toByteArray()));

    if (unmarshalledZoo.animals == null) {
        System.out.println("animals was null");
    } else if (unmarshalledZoo.animals.size() == 2) {
        System.out.println("it worked");
    } else {
        System.out.println("failed!");
    }
}

public interface Animal {
}

@XmlRootElement
public static class Dog implements Animal {

    private String dogProp;

    public String getDogProp() {
        return dogProp;
    }

    public void setDogProp(String dogProp) {
        this.dogProp = dogProp;
    }
}

@XmlRootElement
public static class Cat implements Animal {

    private String catProp;

    public String getCatProp() {
        return catProp;
    }

    public void setCatProp(String catProp) {
        this.catProp = catProp;
    }
}

}

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜