david419
david419

Reputation: 435

Error while Convert xml to Object or Map in Scala using xstream

I am trying to covert an xml to object using xstream:-

  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)

The testing class has been defined as follows:-

class testing {

  private var note = None;

}

I am getting the following error:-

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)

Please help with the above.

Also is there a way to directly convert the xml into a map in scala?

Upvotes: 0

Views: 277

Answers (1)

ars
ars

Reputation: 1639

I have no problem running your code:

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
}

Perhaps your testing class is not in the default package, so it is a packaging issue?

Anyway, how do you expect a variable of None type to store your data? Perhaps you should make it a String or Int. I am not familiar with Xstream, but if you wanted the library to map directly xml into Option, I think you will need to write a custom converter. This applies to converting to/from Maps too.

Upvotes: 1

Related Questions