Scala 中的 JSON 到 XML 并处理 Option() 结果
考虑 Scala 解释器的以下内容:
scala> JSON.parseFull("""{"name":"jack","greeting":"hello world"}""")
res6: Option[Any] = Some(Map(name -> jack, greeting -> hello world))
为什么 Map 在 Some() 中返回?我该如何使用它?
我想将值放入 xml 模板中:
<test>
<name>name goes here</name>
<greeting>greeting goes here</greeting>
</test>
从 Some(thing) 中获取地图并在 xml 中获取这些值的 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))
Why is the Map returned in Some() thing? And how do I work with it?
I want to put the values in an xml template:
<test>
<name>name goes here</name>
<greeting>greeting goes here</greeting>
</test>
What is the Scala way of getting my map out of Some(thing) and getting those values in the xml?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可能应该使用类似这样的内容:
其中:
collect
方法采用Option[A]
上的PartialFunction[A, B]
并且是filter
的组合 (通过谓词)和map
(通过函数)。即:两者等价。当您有一个可选值时,您应该使用
map
、flatMap
、filter
、collect 等来转换程序中的选项,避免通过模式匹配或通过 get 方法提取选项的内容。您不应该永远、永远使用
Option.get
- 这是您做错了的规范标志。应避免模式匹配,因为它代表程序中的分叉,因此会增加圈复杂度 - 您可能希望这样做的唯一一次可能是为了性能实际上,您遇到的问题是
parseJSON 方法是一个
Option[Any]
(之所以是一个Option
,大概是解析可能不成功而Option
> 是一种更优雅的处理方式null
比,好吧,null
)。但我上面的代码的问题是,由于类型擦除,无法在运行时检查
case x: Map[String, String]
(即 scala 可以检查该选项是否包含Map< /code> 但不是
Map
的类型参数都是String
。该代码会给您一个未检查警告。You should probably use something like this:
Where:
The
collect
method onOption[A]
takes aPartialFunction[A, B]
and is a combination offilter
(by a predicate) andmap
(by a function). That is:Are both equivalent. When you have an optional value, you should use
map
,flatMap
,filter
,collect
etc to transform the option in your program, avoiding extracting the option's contents either via a pattern-match or via theget
method. You should never, ever useOption.get
- it is the canonical sign that you are doing it wrong. Pattern-matching should be avoided because it represents a fork in your program and hence adds to cyclomatic complexity - the only time you might wish to do this might be for performanceActually you have the issue that the result of the
parseJSON
method is anOption[Any]
(the reason is that it is anOption
, presumably, is that the parsing may not succeed andOption
is a more graceful way of handlingnull
than, well,null
).But the issue with my code above is that the
case x: Map[String, String]
cannot be checked at runtime due to type erasure (i.e. scala can check that the option contains aMap
but not that theMap
's type parameters are bothString
. The code will get you an unchecked warning.返回
Option
是因为parseFull
根据输入的不同可能有不同的返回值,或者可能根本无法解析输入(给出None
)。因此,除了将键与值关联起来的可选Map
之外,如果 JSON 字符串表示数组,还可以返回可选的List
。示例:
您可能需要模式匹配才能实现您想要的效果,如下所示:
现在,如果您想生成 XML 输出,您可以使用上面的内容来迭代键/值对:
An
Option
is returned becauseparseFull
has different possible return values depending on the input, or it may fail to parse the input at all (givingNone
). So, aside from an optionalMap
which associates keys with values, an optionalList
can be returned as well if the JSON string denoted an array.Example:
You might need pattern matching in order to achieve what you want, like so:
Now, if you want to generate XML output, you can use the above to iterate over the key/value pairs:
parseFull
返回Option
,因为字符串可能不是有效的 JSON(在这种情况下,它将返回None
而不是Some
>)。从
Some
中获取值的常用方法是对其进行模式匹配,如下所示:如果您确定输入始终有效,因此您不需要处理以下情况输入无效,您可以使用
Option
上的get
方法,该方法在None
上调用时会抛出异常。parseFull
returns anOption
because the string may not be valid JSON (in which case it will returnNone
instead ofSome
).The usual way to get the value out of a
Some
is to pattern match against it like this:If you're certain the input will always be valid and so you don't need to handle the case of invalid input, you can use the
get
method on theOption
, which will throw an exception when called onNone
.你有两个不同的问题。
Any
。Option
和Map
内。假设我们有数据:
并假设我们希望在有内容要返回时返回适当的 XML,否则不返回。然后我们可以使用
collect
来收集我们知道如何处理的那些部分:(注意我们如何将映射中的每个条目分开以确保它将一个字符串映射到一个字符串 - 我们否则我们将不知道如何继续。
好吧,现在如果您知道您需要 XML 中的哪些字段,则可以询问它们:
在本例中(成功)会生成哪些字段
。在不成功的情况下会产生
无
。如果您想以
value
形式包装您在地图中找到的任何内容,则需要更多工作,因为 Scala没有很好的标签抽象:它再次产生
(您可以使用
get
来获取Option
的内容,但如果>选项
为空(即无
)。)You have two separate problems.
Any
.Option
and aMap
.Let's suppose we have the data:
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:(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:
Okay, that's better! Now if you know which fields you want in your XML, you can ask for them:
which in this (successful) case produces
and in an unsuccessful case would produce
None
.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:which again produces
(You can use
get
to get the contents of anOption
, but it will throw an exception if theOption
is empty (i.e.None
).)