将Json转换为Map [String,String]

将Json转换为Map [String,String]

问题描述:

我输入了json之类的

I have input json like

{"a": "x", "b": "y", "c": "z", .... }

我想将此json转换为Map [String,String]

I want to convert this json to a Map like Map[String, String]

因此基本上是键值对的映射.

so basically a map of key value pairs.

如何使用circe来做到这一点?

How can I do this using circe?

请注意,我不知道Json中将显示哪些键"a","b","c".我所知道的是,它们将始终是字符串,而永远不会是任何其他数据类型.

Note that I don't know what keys "a", "b", "c" will be present in Json. All I know is that they will always be strings and never any other data type.

我在这里查看了自定义解码器 https://circe.github.io /circe/codecs/custom-codecs.html ,但仅当您知道标记名称时它们才起作用.

I looked at Custom Decoders here https://circe.github.io/circe/codecs/custom-codecs.html but they work only when you know the tag names.

我在杰克逊(Jackson)找到了一个做到这一点的例子.但不是大约

I found an example to do this in Jackson. but not in circe

import com.fasterxml.jackson.module.scala.DefaultScalaModule
import com.fasterxml.jackson.databind.ObjectMapper

val data = """
    {"a": "x", "b", "y", "c": "z"}
"""
val mapper = new ObjectMapper
mapper.registerModule(DefaultScalaModule)
mapper.readValue(data, classOf[Map[String, String]])

尽管其他答案中的解决方案有效,但它们的冗长程度超过了必要.现成的圈子提供了一个隐式的Decoder[Map[String, String]]实例,因此您可以编写以下内容:

While the solutions in the other answer work, they're much more verbose than necessary. Off-the-shelf circe provides an implicit Decoder[Map[String, String]] instance, so you can just write the following:

scala> val doc = """{"a": "x", "b": "y", "c": "z"}"""
doc: String = {"a": "x", "b": "y", "c": "z"}

scala> io.circe.parser.decode[Map[String, String]](doc)
res0: Either[io.circe.Error,Map[String,String]] = Right(Map(a -> x, b -> y, c -> z))

Decoder[Map[String, String]]实例是在Decoder伴随对象中定义的,因此它始终可用-您不需要任何导入,其他模块等.Circe为具有合理实例的大多数标准库类型提供了此类实例.例如,如果要将JSON数组解码为List[String],则无需构建自己的Decoder[List[String]],您只需使用来自Decoder随播对象的隐式作用域中的那个即可.

The Decoder[Map[String, String]] instance is defined in the Decoder companion object, so it's always available—you don't need any imports, other modules, etc. Circe provides instances like this for most standard library types with reasonable instances. If you want to decode a JSON array into a List[String], for example, you don't need to build your own Decoder[List[String]]—you can just use the one in implicit scope that comes from the Decoder companion object.

这不仅是解决此问题的详细方法,而且是解决此问题的推荐方法.手动构造一个显式的解码器实例并将其从Either转换为Try以进行解析和解码操作既不必要又容易出错(如果您确实需要以TryOption或其他名称结尾,几乎当然最好在最后这样做).

This isn't just a less verbose way to solve this problem, it's the recommended way to solve it. Manually constructing an explicit decoder instance and converting from Either to Try to compose parsing and decoding operations is both unnecessary and error-prone (if you do need to end up with Try or Option or whatever, it's almost certainly best to do that at the end).