JSON to XML in Scala and dealing with Option() result

前端 未结 4 2002
轻奢々
轻奢々 2021-01-23 01:25

Consider the following from the Scala interpreter:

scala> JSON.parseFull(\"\"\"{\"name\":\"jack\",\"greeting\":\"hello world\"}\"\"\")
res6: Option[Any] = Som         


        
4条回答
  •  攒了一身酷
    2021-01-23 01:36

    An Option is returned because parseFull has different possible return values depending on the input, or it may fail to parse the input at all (giving None). So, aside from an optional Map which associates keys with values, an optional List can be returned as well if the JSON string denoted an array.

    Example:

    scala> import scala.util.parsing.json.JSON._
    import scala.util.parsing.json.JSON._
    
    scala> parseFull("""{"name":"jack"}""")
    res4: Option[Any] = Some(Map(name -> jack))
    
    scala> parseFull("""[ 100, 200, 300 ]""")
    res6: Option[Any] = Some(List(100.0, 200.0, 300.0))
    

    You might need pattern matching in order to achieve what you want, like so:

    scala> parseFull("""{"name":"jack","greeting":"hello world"}""") match {
         |   case Some(m) => Console println ("Got a map: " + m)
         |   case _ =>
         | }
    Got a map: Map(name -> jack, greeting -> hello world)
    

    Now, if you want to generate XML output, you can use the above to iterate over the key/value pairs:

    import scala.xml.XML
    
    parseFull("""{"name":"jack","greeting":"hello world"}""") match {
      case Some(m: Map[_,_]) =>
        
          {
            m map { case (k,v) =>
              XML.loadString("<%s>%s".format(k,v,k))
            }
          }
        
    
      case _ =>
    }
    

提交回复
热议问题