使用 json4s 将 [String,Any] 映射到压缩 json 字符串 [英] Map[String,Any] to compact json string using json4s
问题描述
我目前正在从不同的数据源中提取一些指标并将它们存储在 Map[String,Any]
类型的映射中,其中键对应于指标名称,值对应于指标值.我需要它或多或少是通用的,这意味着值类型可以是原始类型或原始类型列表.
I am currently extracting some metrics from different data sources and storing them in a map of type Map[String,Any]
where the key corresponds to the metric name and the value corresponds to the metric value. I need this to be more or less generic, which means that values types can be primitive types or lists of primitive types.
我想将此映射序列化为 JSON 格式的字符串,为此我使用了 json4s
库.问题是这似乎不可能,我看不到可能的解决方案.我希望像下面这样的东西开箱即用:)
I would like to serialize this map to a JSON-formatted string and for that I am using json4s
library. The thing is that it does not seem possible and I don't see a possible solution for that. I would expect something like the following to work out of the box :)
val myMap: Map[String,Any] = ... // extract metrics
val json = myMap.reduceLeft(_ ~ _) // create JSON of metrics
浏览源代码我已经看到 json4s
提供隐式转换,以便将原始类型转换为 JValue
并转换 Traversable[A]/Map[String,A]/Option[A]
到 JValue
的(在从 A
到 JValue 的隐式转换可用的限制下
,我理解它实际上意味着 A
是一种原始类型).~
运算符提供了一种从 JField
构造 JObject
的好方法,它只是 (字符串,JValue)
.
Navigating through source code I've seen json4s
provides implicit conversions in order to transform primitive types to JValue
's and also to convert Traversable[A]/Map[String,A]/Option[A]
to JValue
's (under the restriction of being available an implicit conversion from A
to JValue
, which I understand it actually means A
is a primitive type). The ~
operator offers a nice way of constructing JObject
's out of JField
's, which is just a type alias for (String, JValue)
.
在这种情况下,映射值类型是 Any
,因此不会发生隐式转换,因此编译器会抛出以下错误:
In this case, map values type is Any
, so implicit conversions don't take place and hence the compiler throws the following error:
value ~ is not a member of (String, Any)
[error] val json = r.reduceLeft(_ ~ _)
是否有针对我想要完成的任务的解决方案?
Is there a solution for what I want to accomplish?
推荐答案
由于你实际上只是在寻找 myMap
的 JSON 字符串表示,你可以使用 Serialization
直接对象.这是一个小例子(如果使用原生版本的 json4s 将导入更改为 org.json4s.native.Serialization
):
Since you are actually only looking for the JSON string representation of myMap
, you can use the Serialization
object directly. Here is a small example (if using the native version of json4s change the import to org.json4s.native.Serialization
):
EDIT:添加了格式
隐式
import org.json4s.jackson.Serialization
implicit val formats = org.json4s.DefaultFormats
val m: Map[String, Any] = Map(
"name "-> "joe",
"children" -> List(
Map("name" -> "Mary", "age" -> 5),
Map("name" -> "Mazy", "age" -> 3)
)
)
// prints {"name ":"joe","children":[{"name":"Mary","age":5},{"name":"Mazy","age":3}]}
println(Serialization.write(m))
这篇关于使用 json4s 将 [String,Any] 映射到压缩 json 字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!