How to convert json string to scala map?

I have a nested json whose structure is not defined. It may be different each time it starts, as I am reading from a deleted file. I need to convert this json to a map of type Map[String, Any] . I tried to look into json4s and Jackson parsers, but they don't seem to solve this problem. Does anyone know how I can achieve this?

Example line:

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

The nesting level can be arbitrary and not predetermined.
To help use:
I have a [String, Any] map that I need to save to a file as a backup. So I convert it to json string and save to file. Now every time I get new data, I need to get json from the file, convert it to a map again and do some calculations. I can’t save the card in memory, as I would lose it if my work failed.
I need a solution that converts the json string back to the original map that I had before I converted it.

+6
source share
2 answers

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]] } 

Maybe you did not define an implicit val type Formats ? Also note that you do not need to have an implicit val in each and every method while it is in scope.

+6
source

You can use the following code to parse a JSON string in Map[String, Any]

 val jsonMap = parse(jsonString).values.asInstanceOf[Map[String, Any]] 

However, this is not typeafe and should therefore be used with caution when retrieving values ​​from the map.

+1
source

Source: https://habr.com/ru/post/986091/


All Articles