yAsH
yAsH

Reputation: 3405

Scala - Writing Json object to file and reading it

I have a Map like below

val map : scala.collection.mutable.Map[String,Any] = Map(
  dummy1 -> ["cat1", "hash1", 101, 1373269076, {"1" : ["dummy", "dummy", "dummy"]}],
  dummy2 -> ["cat1", "hash1", 102, 1373269076, {"2" : ["dummy", "dummy", "dummy"]}],
  dummy3 -> ["cat1", "hash1", 103, 1373269076, {"3" : ["dummy", "dummy", "dummy"]}]
)

I converted it into a Json string and then wrote it into a file with the code below

Some(new PrintWriter("foo.txt")).foreach{p =>
  p.write(JSONObject(map.toMap).toString()); p.close
}

Am able to read the Json string from the file using

val json_string = scala.io.Source.fromFile("foo.txt").getLines.mkString

How do I get my map back from the Json string above?

EDIT: Am able to read the map with

val map1 = JSON.parseFull(json_string).get.asInstanceOf[Map[String,Any]]

But, this process is taking more time as the size of the map increases.

Upvotes: 18

Views: 43052

Answers (3)

Powers
Powers

Reputation: 19308

ujson is the best modern solution to read and write JSON.

Here's how to build up an object and write it to disk:

val weirdData = ujson.Obj(
  "something1" -> ujson.Arr("cat1", "hash1", 101),
  "something2" -> ujson.Arr("cat2", "hash2", 102),
  "something3" -> ujson.Arr("cat3", "hash3", 103)
)
os.write(os.pwd/"tmp"/"weird_data.json", weirdData)

Here are the contents of the weird_data.json file:

{
  "something1":["cat1","hash1",101],
  "something2":["cat2","hash2",102],
  "something3":["cat3","hash3",103]
}

You can easily read this data from a JSON file to a ujson object.

val jsonString = os.read(os.pwd/"tmp"/"weird_data.json")
val data = ujson.read(jsonString)
// here's what data contains
ujson.Value.Value = Obj(
  LinkedHashMap(
    "something1" -> Arr(ArrayBuffer(Str("cat1"), Str("hash1"), Num(101.0))),
    "something2" -> Arr(ArrayBuffer(Str("cat2"), Str("hash2"), Num(102.0))),
    "something3" -> Arr(ArrayBuffer(Str("cat3"), Str("hash3"), Num(103.0)))
  )
)

Here's how to grab a value from the ujson object.

data("something2")(1).str // "hash2"

See here for more details on writing JSON data with Scala.

Upvotes: 3

Greg
Greg

Reputation: 5588

I actually got a lot more use from json4s. The documentation is much more clear and comprehensive, and the usage seems slightly easier.

A similar operation to the one you are requesting would look like this

import org.json4s.native.JsonFormats.parse

... get your json string ...
val parsedJson = parse(json)
val extractedJson = parsedJson.extract[MyClass]

Upvotes: 5

Bruno Grieder
Bruno Grieder

Reputation: 29814

Try using a likely faster (and more thorough) mapper.

I would recommend using JacksMapper which wraps the excellent Jackson for a more pleasant Scala usage.

Serializing to JSON becomes as simple as

val json = JacksMapper.writeValueAsString[MyClass](instance)

... and deserializing

val obj = JacksMapper.readValue[MyClass](json)

(edit)

You can make also writing and reading simple one-liners using FileUtils from commons-io doing

val json = FileUtils readFileToString (file, encoding)

and

FileUtils write (file, json, encoding) 

Upvotes: 13

Related Questions