如何将json字符串转换为scala映射? [英] How can I convert a json string to a scala map?

查看:170
本文介绍了如何将json字符串转换为scala映射?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个嵌套的json,其结构未定义。由于我从远程文件中读取,因此每次运行时都可能不同。我需要将这个json转换为 Map [String,Any] 类型的映射。我试着研究json4s和jackson解析器,但它们似乎没有解决我的这个问题。
有谁知道我怎么做到这一点?

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 jackson parsers but they don't seem to solve this issue I have. Does anyone know how I can achieve this?

示例字符串:

{"body":{
    "method":"string",
    "events":"string",
    "clients":"string",
    "parameter":"string",
    "channel":"string",
    "metadata":{
        "meta1":"string",
        "meta2":"string",
        "meta3":"string"
    }
},
"timestamp":"string"}

嵌套级别可以是任意的,也不是预定义的。

帮助用例:

I有一个Map [String,Any]我需要存储在一个文件中作为备份。所以我将它转换为json字符串并将其存储在一个文件中。现在,每当我获得新数据时,我需要从文件中获取json,再次将其转换为地图并执行一些计算。我无法将地图存储在内存中,因为如果我的工作失败,我会失去它。

我需要一个解决方案,将json字符串转换回我转换之前的原始地图。

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.

推荐答案

我用 json4s 3.2.11尝试了以下方法,它可以工作:

I tried the following method with json4s 3.2.11 and it works:

import org.json4s._
import org.json4s.jackson.JsonMethods._

//...
def jsonStrToMap(jsonStr: String): Map[String, Any] = {
  implicit val formats = org.json4s.DefaultFormats

  parse(jsonStr).extract[Map[String, Any]]
}

也许你没有定义类型格式隐式val ?另请注意,只要在范围内 findable ,您就不需要在每个方法中都有隐式val

Maybe you didn't define the implicit val of type Formats? Note also that you don't need to have an implicit val within every and each method as long as it's findable in the scope.

这篇关于如何将json字符串转换为scala映射?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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