如何在Scala中使用JAXB取消/编组列表?

时间:2013-11-27 11:52:50

标签: xml scala jaxb

我正在尝试将一些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
}

1 个答案:

答案 0 :(得分:0)

正如评论中所注意到的那样,Java集合工作正常。

我发布了代码here