在 Scala 中将 JSON 转换为 XML 并处理 Option() 结果 [英] JSON to XML in Scala and dealing with Option() result

查看:71
本文介绍了在 Scala 中将 JSON 转换为 XML 并处理 Option() 结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑来自 Scala 解释器的以下内容:

Consider the following from the Scala interpreter:

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

为什么 Map 会在 Some() 中返回?我该如何使用它?

Why is the Map returned in Some() thing? And how do I work with it?

我想把这些值放在一个 xml 模板中:

I want to put the values in an xml template:

<test>
  <name>name goes here</name>
  <greeting>greeting goes here</greeting>
</test>

从 Some(thing) 中获取我的地图并在 xml 中获取这些值的 Scala 方法是什么?

What is the Scala way of getting my map out of Some(thing) and getting those values in the xml?

推荐答案

您有两个不同的问题.

  1. 输入为Any.
  2. 您的数据位于 OptionMap 中.
  1. It's typed as Any.
  2. Your data is inside an Option and a Map.

假设我们有数据:

val x: Option[Any] = Some(Map("name" -> "jack", "greeting" -> "hi"))

并假设我们想要返回适当的 XML,如果有东西要返回,但不是其他的.然后我们可以使用 collect 来收集那些我们知道如何处理的部分:

and suppose that we want to return the appropriate XML if there is something to return, but not otherwise. Then we can use collect to gather those parts that we know how to deal with:

val y = x collect {
  case m: Map[_,_] => m collect {
    case (key: String, value: String) => key -> value
  }
}

(注意我们如何将映射中的每个条目分开以确保它将字符串映射到字符串——否则我们将不知道如何进行.我们得到:

(note how we've taken each entry in the map apart to make sure it maps a string to a string--we wouldn't know how to proceed otherwise. We get:

y: Option[scala.collection.immutable.Map[String,String]] =
  Some(Map(name -> jack, greeting -> hi))

好的,这样更好!现在,如果您知道在您的 XML 中需要哪些字段,您可以要求它们:

Okay, that's better! Now if you know which fields you want in your XML, you can ask for them:

val z = for (m <- y; name <- m.get("name"); greet <- m.get("greeting")) yield {
  <test><name>{name}</name><greeting>{greet}</greeting></test>
}

在这个(成功)的情况下产生

which in this (successful) case produces

z: Option[scala.xml.Elem] =
  Some(<test><name>jack</name><greeting>hi</greeting></test>)

并且在不成功的情况下会产生 None.

and in an unsuccessful case would produce None.

如果您想将您碰巧在地图中找到的任何内容包装在 value</key> 的形式中,则需要做更多的工作,因为 Scala 没有标签抽象:

If you instead want to wrap whatever you happen to find in your map in the form <key>value</key>, it's a bit more work because Scala doesn't have a good abstraction for tags:

val z = for (m <- y) yield <test>{ m.map { case (tag, text) => xml.Elem(null, tag, xml.Null, xml.TopScope, xml.Text(text)) }}</test>

再次产生

z: Option[scala.xml.Elem] =
  Some(<test><name>jack</name><greeting>hi</greeting></test>)

(可以使用get来获取Option的内容,但是如果Option为空会抛出异常(即).)

(You can use get to get the contents of an Option, but it will throw an exception if the Option is empty (i.e. None).)

这篇关于在 Scala 中将 JSON 转换为 XML 并处理 Option() 结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆