使用xstream将xml转换为对象或映射到Scala时出错

时间:2016-08-28 10:08:50

标签: xml scala object xstream

我试图使用xstream将xml转换为对象: -

  def convert(xml: String) = {

      val xstream = new XStream(new DomDriver)
      val convertedMap:testing =  xstream.fromXML(xml).asInstanceOf[testing];
      convertedMap
  }
  val justtest:String = "<testing><note>5</note></testing>"
  convert(justtest)

测试类的定义如下: -

class testing {

  private var note = None;

}

我收到以下错误: -

java.lang.InstantiationError: testing
    at sun.reflect.GeneratedSerializationConstructorAccessor28.newInstance(sum.sc)
    at java.lang.reflect.Constructor.newInstance(sum.sc:419)
    at com.thoughtworks.xstream.converters.reflection.Sun14ReflectionProvider.newInstance(sum.sc:71)
    at com.thoughtworks.xstream.converters.reflection.AbstractReflectionConverter.instantiateNewInstance(sum.sc:424)
    at com.thoughtworks.xstream.converters.reflection.AbstractReflectionConverter.unmarshal(sum.sc:229)
    at com.thoughtworks.xstream.core.TreeUnmarshaller.convert(sum.sc:68)
    at com.thoughtworks.xstream.core.AbstractReferenceUnmarshaller.convert(sum.sc:61)
    at com.thoughtworks.xstream.core.TreeUnmarshaller.convertAnother(sum.sc:62)
    at com.thoughtworks.xstream.core.TreeUnmarshaller.convertAnother(sum.sc:46)
    at com.thoughtworks.xstream.core.TreeUnmarshaller.start(sum.sc:130)
    at com.thoughtworks.xstream.core.AbstractTreeMarshallingStrategy.unmarshal(sum.sc:28)
    at com.thoughtworks.xstream.XStream.unmarshal(sum.sc:1054)
    at com.thoughtworks.xstream.XStream.unmarshal(sum.sc:1038)
    at com.thoughtworks.xstream.XStream.fromXML(sum.sc:909)
    at com.thoughtworks.xstream.XStream.fromXML(sum.sc:900)
    at #worksheet#.convert(sum.sc:26)
    at #worksheet#.#worksheet#(sum.sc:30)

请帮助解决上述问题。

还有一种方法可以直接将xml转换为scala中的地图吗?

1 个答案:

答案 0 :(得分:1)

运行代码没问题:

import com.thoughtworks.xstream.XStream
import com.thoughtworks.xstream.io.xml.DomDriver

object Main {
  def main(args: Array[String]): Unit = {
    val justtest:String = "<Testing><note>5</note></Testing>"
    convert(justtest)
  }

  def convert(xml: String) = {
    val xstream = new XStream(new DomDriver)
    val convertedMap: Testing =  xstream.fromXML(xml).asInstanceOf[Testing]
    convertedMap
  }
}

class Testing {
  private var note = None
}

也许你的testing类不在默认包中,所以这是一个包装问题?

无论如何,您如何期望None类型的变量存储您的数据?也许你应该把它变成String或Int。我不熟悉Xstream,但如果您希望库直接将xml映射到Option中,我认为您需要编写自定义转换器。这也适用于转换到地图或从地图转换。