Scala - Writing Json object to file and reading it

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) 

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]

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.