使用Scala中的命名空间和标记将json转换为XML

时间:2015-11-17 17:55:51

标签: scala xstream

我有一个像这样的json文档:

{"orderNumber": "12345",
"date": "11/05/2011",
"fromInventoryLocation": "New York",
"toLocation": "Los Angeles",
"shippingMethod": "Ground",
"shipDate": "11/25/2014",
"shipTo": "123 Main St.",
"Items": [
   {"item": "shirt", "quantity": "2", "orderPriority": "Standard"}, 
]}

我使用:

初始化XStream转换器

val xstreamIB = xstream.XStreamConversions(new XStream(new DomDriver))

我使用案例类Shipment来创建对象并将其传递给:

val xmlIB = xstreamIB.toXML(Shipment)

输出XML文件返回:

<Shipment>
  <OrderNumber>12345</OrderNumber>
  <Date>11/05/2011</Date>
  <Address>
    <Street>123 Main St.</Street>
  </Address>
  <Etc>
    <Ex>...</Ex>
  </Etc>
</Shipment

接收API需要2件事。开始发货标签中的命名空间; <Shipment xmlns="namespace">,以及地址标记中的标记; <Address type = "shipping">。我尝试使用.alias,但它修改了open和closing标签;抛出错误。

有没有办法将命名空间和令牌添加到开始标记中?

1 个答案:

答案 0 :(得分:0)

我能够使用StaxDriver而不是DomDriver来获取xml命名空间。以下代码有效:

val qmap = new QNameMap
  qmap.setDefaultNamespace("urn:namespace")
  val xmlOut = xstream.XStreamConversions(new XStream(new StaxDriver(qmap)))
val xml = xmlOut.toXML(Shipment)