我正在尝试将一些XML读入案例类,反之亦然。一切似乎都很好,但列表属性。我不知道例外:
Exception in thread "main" javax.xml.bind.UnmarshalException: Unable to create an instance of scala.collection.immutable.List
不过,可能是JAXB根本不适合我的目的,我应该使用原生scala方式进行XML处理?但我的目标XSD非常大,我认为这会很痛苦。
这是我的代码:
package common
import java.io.StringReader
import scala.annotation.target.field
import javax.xml.bind.annotation._
import javax.xml.bind.annotation.adapters._
import javax.xml.bind._
import common.Types.{xmlTypeAdapter, xmlElement}
@XmlRootElement(name = "person")
@XmlAccessorType(XmlAccessType.FIELD)
case class Person(
@xmlElement(required = true) fullname: String,
username: String,
age: Int,
favNumbers: List[Int]){
private def this() = this("", "", 0, List())
}
object JaxbTest {
val context = JAXBContext.newInstance(classOf[Person])
def main(args: Array[String]) {
val personXml1 = "<person><fullname>Martin Krasser</fullname><username>mrt1nz</username><age>30</age><favNumbers><favNumber>73</favNumber><favNumber>47</favNumber></favNumbers></person>"
assert(context.createUnmarshaller().unmarshal(new StringReader(personXml1)) ==
Person("Martin Krasser", "mrt1nz", 30, List(73,47)))
context.createMarshaller.marshal(Person("Martin Krasser", "mrt1nz", 30, List(73,47)), System.out)
}
}
package object Types {
type xmlElement = XmlElement@field
type xmlTypeAdapter = XmlJavaTypeAdapter@field
}