XML to JSON with Scala

前端 未结 3 626
滥情空心
滥情空心 2020-12-30 10:48

For a XML snippet like this:

val fruits =

  
    apple
    ok
  

        
相关标签:
3条回答
  • 2020-12-30 11:12

    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)
    
    0 讨论(0)
  • 2020-12-30 11:12

    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))
    
    0 讨论(0)
  • 2020-12-30 11:15

    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.

    0 讨论(0)
提交回复
热议问题