For a XML snippet like this:
val fruits =
apple
ok
This might be relevant. Here is my solution using 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)
org.json4s makes this pretty simple:
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))
I think you should use ScalaXB to turn the XML into scala classes and then write the appropriate toJson bits to output Json.
Should work a treat.