如何将 json 字符串转换为 Scala 映射?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29908297/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I convert a json string to a scala map?
提问by Udit Mehta
I have a nested json whose structure is not defined. It can be different each time I run since I am reading from a remote file. I need to convert this json into a map of type Map[String, Any]. I tried to look into json4s and Hymanson parsers but they don't seem to solve this issue I have.
Does anyone know how I can achieve this?
我有一个未定义结构的嵌套 json。因为我是从远程文件中读取的,所以每次运行时它可能会有所不同。我需要将此 json 转换为类型为 的地图Map[String, Any]。我试图研究 json4s 和 Hymanson 解析器,但它们似乎没有解决我遇到的这个问题。有谁知道我如何实现这一目标?
Example string:
示例字符串:
{"body":{
"method":"string",
"events":"string",
"clients":"string",
"parameter":"string",
"channel":"string",
"metadata":{
"meta1":"string",
"meta2":"string",
"meta3":"string"
}
},
"timestamp":"string"}
The level of nesting can be arbitrary and not predefined.
To help with the use case:
I have a Map[String,Any] which I need to store in a file as backup. So I convert it to a json string and store it in a file. Now everytime I get new data, I need to get the json from the file, convert it to a map again and perform some computation. I cannot store the map in memory since I would lose that if my job fails.
I need a solution that would convert the json string back to the original map I had before i converted it.
嵌套级别可以是任意的,并且不是预定义的。
为了帮助使用案例:
我有一个 Map[String,Any],我需要将它存储在一个文件中作为备份。所以我将其转换为 json 字符串并将其存储在文件中。现在每次获取新数据时,我都需要从文件中获取 json,再次将其转换为地图并执行一些计算。我无法将地图存储在内存中,因为如果我的工作失败,我会丢失它。
我需要一个解决方案,将 json 字符串转换回我转换之前的原始地图。
回答by lambdista
I tried the following method with json4s3.2.11 and it works:
我在json4s3.2.11 中尝试了以下方法并且它有效:
import org.json4s._
import org.json4s.Hymanson.JsonMethods._
//...
def jsonStrToMap(jsonStr: String): Map[String, Any] = {
implicit val formats = org.json4s.DefaultFormats
parse(jsonStr).extract[Map[String, Any]]
}
Maybe you didn't define the implicit valof type Formats? Note also that you don't need to have an implicit valwithin every and each method as long as it's findablein the scope.
也许你没有定义implicit valof 类型Formats?另请注意,implicit val只要在范围内可找到,您就不需要在每个方法中都有一个。
回答by user297112
You can use the following code to parse a JSON string into a Map[String, Any]
您可以使用以下代码将 JSON 字符串解析为 Map[String, Any]
val jsonMap = parse(jsonString).values.asInstanceOf[Map[String, Any]]
However, this is not typesafeand hence should be used with caution when extracting values from the map.
但是,这不是类型安全的,因此在从地图中提取值时应谨慎使用。

