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

Posted 张松任

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了用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;

以上是关于用Xstream时候遇到的两个小异常的主要内容,如果未能解决你的问题,请参考以下文章

SpringBoot使用devtools导致的类型转换异常

小片段中的 ORA-06512 [重复]

谁用过Xstream 用其生成带有cdata标签的xml解析带有cdata标签的xml

PHP必用代码片段

在 Android 上使用 omitField() 的 Proguard 和 XStream

片段中的TextView在Android Studio中返回Null