用Xstream时候遇到的两个小异常

第一个

com.thoughtworks.xstream.converters.ConversionException: Cannot construct ClassXXX as it does not have a no-args constructor : Cannot construct yourpackage.yourclass as it does not have a no-args constructor

搜了一下才发现是版本的问题:

我用的是JDK7+XStream1.3.1

你可以换回JDK1.6或者升级XStream到最新版本。

参考:http://stackoverflow.com/questions/7966817/xstream-unmarshalling-type-specified-in-xml-not-visible

复制过来:

I got to the bottom of it - turns out xstream should handle that xml (it doesn't need a no-args constructor), the issue arose because I was using jdk 7 with an older version of xstream (1.3.1). See here http://code.google.com/p/pitestrunner/issues/detail?id=4. Moving back to jdk 6 fixed the issue (for various reasons i can't upgrade).

Before I realised that I did write a converter that worked for RandomAccessSubList if anyone needs it:

public class RandomAccessSubListConverter extends CollectionConverter {

public RandomAccessSubListConverter(Mapper mapper) {
    super(mapper); 
} 

@Override
public boolean canConvert(Class arg0) {     
    return arg0.getName().equals("java.util.RandomAccessSubList");
}

@Override
public Object unmarshal(HierarchicalStreamReader reader,
        UnmarshallingContext context) {        
    reader.moveDown();
    ArrayList arrayList = new ArrayList();
    populateCollection(reader, context, arrayList);
    reader.moveUp();
    return arrayList;
}

Thanks to anyone who was looking into for me!

我选择用最新的版本来解决,然后就遇到了第二个问题:

第二个

java.lang.NoClassDefFoundError: org/xmlpull/v1/XmlPullParserFactory

在初始化你的XStream的时候,在构造函数里面传入入:new DomDriver()

参考:http://blog.csdn.net/chenallen1025/article/details/8030552

复制过来:

1.抛出的异常信息如下:

2.原因:

应该改成:

XStream xstream=new XStream(new DomDriver()); //注意:不是new Xstream(); 否则报上面的错
xstream.processAnnotations(PersonBean.class); //如果是用注解的方式,这句不能少
PersonBean person=(PersonBean)xstream.fromXML(xmlStr);
System.out.println("person=firstname=="+person.getFirstName());
return person;
posted @ 2013-10-14 14:01  immars!  阅读(1579)  评论(0编辑  收藏  举报