使用Scala将XML转换为JSON
对于这样的XML代码段:使用Scala将XML转换为JSON,scala,Scala,对于这样的XML代码段: val fruits = <fruits> <fruit> <name>apple</name> <taste>ok</taste> </fruit> <fruit> <name>banana</name> <taste>better</taste> </fruit>
val fruits =
<fruits>
<fruit>
<name>apple</name>
<taste>ok</taste>
</fruit>
<fruit>
<name>banana</name>
<taste>better</taste>
</fruit>
</fruits>
将返回类型为scala.xml.NodeSeq
的序列,其中包含所有结果和子节点
将其转换为JSON对象列表的最佳方式是什么?我正在尝试将我的水果列表发送回浏览器。我查看了scala.util.parsing.json.JSONObject
和scala.util.parsing.json.JSONArray
,但我不知道如何从NodeSeq到后者
如果可能的话,我很想看看普通Scala代码是如何实现的。我认为您应该使用将XML转换为Scala类,然后编写适当的toJson位来输出Json
应该有治疗作用。可能相关。以下是我的解决方案:
导入scala.xml_
导入cc.spray.json_
导入cc.spray.json.DefaultJsonProtocol_
隐式对象NodeFormat扩展JsonFormat[Node]{
def写入(节点:节点)=
if(node.child.count(u.isInstanceOf[Text])==1)
JsString(node.text)
其他的
JsObject(node.child.collect{
案例e:Elem=>e.label->write(e)
}: _*)
def read(jsValue:jsValue)=null//未实现
}
瓦尔水果=
苹果
真的
真的
香蕉
更好的
val json=“”[{”name:“apple”,“taste:{”sweet:“true”,“juicy:“true”}},{”name:“banana”,“taste:“better”}]”“
断言((水果\\“水果”).toSeq.toJson.toString==json)
org.json4s使这一点非常简单:
import org.json4s.Xml.toJson
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>
println(toJson(fruits))
import org.json4s.Xml.toJson
瓦尔水果=
苹果
真的
真的
香蕉
更好的
println(toJson(水果))
这看起来不错,但您的示例无法运行。我得到以下信息:error:notfound:value JsField.@jacobusroops,仍然使用1.0.1版本的spray json。在1.1.0中确实没有JsField
类。用元组替换了它。很有魅力,谢谢。得到一段可运行的代码,而不仅仅是一段代码(+1,表示:-),总是很好的。仅供参考,最近更新了JSON,看起来JsonFormat
有movedAJsonWriter
在这里更合适,因为这意味着您不需要让悬空的read
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)
import org.json4s.Xml.toJson
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>
println(toJson(fruits))