Search code examples
javaxmlxstream

XStream cannot deserialize XML due to NoClassDefFoundError


So I am trying to serialize a simple object to an XML file using the XStream library.

These result into the following exception complaining about class Person not being found. I've tried adding XStream annotations to the Person class but this had no success either.

What is the correct way to (de)serialize objects using the XStream library for

Exception in thread "main" java.lang.NoClassDefFoundError: org/xmlpull/v1/XmlPullParserException
    at com.thoughtworks.xstream.XStream.<init>(XStream.java:350)
    at XMLTest.main(XMLTest.java:10)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)
Caused by: java.lang.ClassNotFoundException: org.xmlpull.v1.XmlPullParserException
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 7 more

For completeness I am adding my code below.

import com.thoughtworks.xstream.XStream;

public class XMLTest {

    public static void main(String[] args) {

        Person john = new Person("John", "Doe", 1234);

        XStream xstream = new XStream();
        String xml = xstream.toXML(john);

        Person newJohn = (Person) xstream.fromXML(xml);

        System.out.println("Hi " + newJohn.getFirstname());
    }
}

and

public class Person {
    private String firstname;
    private String lastname;
    private int age;

    public Person(String firstname, String lastname, int age) {
        this.firstname = firstname;
        this.lastname = lastname;
        this.age = age;
    }

    public String getFirstname() {
        return firstname;
    }

    public void setFirstname(String firstname) {
        this.firstname = firstname;
    }

    public String getLastname() {
        return lastname;
    }

    public void setLastname(String lastname) {
        this.lastname = lastname;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

Solution

  • Use

    XStream xstream = new XStream(new StaxDriver());
    

    instead.

    The explanation is that if you do

    XStream xstream = new XStream(new StaxDriver());
    

    then you require xstream-[version].jar, xpp3-[version].jar and xmlpull-[version].jar in the classpath." but XStream xstream = new XStream(new StaxDriver()); does not require XPP3 library starting with Java 6

    a very simple explanation and more information can be obtain in the repo-source