对于这样的XML代码段:
val fruits =
<fruits>
<fruit>
<name>apple</name>
<taste>ok</taste>
</fruit>
<fruit>
<name>banana</name>
<taste>better</taste>
</fruit>
</fruits>
Run Code Online (Sandbox Code Playgroud)
做类似的事情:
fruits \\ "fruit"
Run Code Online (Sandbox Code Playgroud)
将返回一个类型序列,scala.xml.NodeSeq其中包含所有水果和子节点.
将此转换为JSON对象列表的最佳方法是什么?我正在尝试将我的水果列表发送回浏览器.我一看scala.util.parsing.json.JSONObject和scala.util.parsing.json.JSONArray,但我不知道如何从NodeSeq获得后者的任何人.
如果可能的话,我很想看看它是如何使用普通的Scala代码完成的.
elb*_*ich 16
这可能是相关的.这是我使用spray-json的解决方案:
import scala.xml._
import cc.spray.json._
import cc.spray.json.DefaultJsonProtocol._
implicit object NodeFormat extends JsonFormat[Node] {
def write(node: Node) =
if (node.child.count(_.isInstanceOf[Text]) == 1)
JsString(node.text)
else
JsObject(node.child.collect {
case e: Elem => e.label -> write(e)
}: _*)
def read(jsValue: JsValue) = null // not implemented
}
val fruits =
<fruits>
<fruit>
<name>apple</name>
<taste>
<sweet>true</sweet>
<juicy>true</juicy>
</taste>
</fruit>
<fruit>
<name>banana</name>
<taste>better</taste>
</fruit>
</fruits>
val json = """[{"name":"apple","taste":{"sweet":"true","juicy":"true"}},{"name":"banana","taste":"better"}]"""
assert((fruits \\ "fruit").toSeq.toJson.toString == json)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9104 次 |
| 最近记录: |