JSON
ScalaCollider – saving presets with json
On 20, Jun 2011 | No Comments | In code, Uncategorized | By admin
Sometimes it is useful to save presets when working with ScalaCollider. In Supercollider this is usually done with
writeArchive
and
readArchive
, which can be called on any object that does not contain open functions. After review several possibilities to do the same in scala, I found that the easiest is to use lift-json for JSON parsing and generation. JSON is a human readable format, which is quite convenient.
The easiest way to save a preset would be using case classes to hold the data, since lift-json can automatically serialize and deserialize them:
import java.io.{FileWriter} import net.liftweb.json._ import net.liftweb.json.Serialization.{write,read} import scala.io.Source._ object TestJsonSerialization { def main(args: Array[String]) { implicit val formats = DefaultFormats case class Person(name: String, address: Option[String], num:List[Int]) case class Container(persons:List[Person]) val people = Container(List(Person("joe", None, List(1,2,3,4)), Person("jack", Some("NY grand central"), List(5,6,7,8)))) //write values to disk val fw = new FileWriter("test.txt") fw.write(write(people)) fw.close() //get values back val jsonString = fromFile("test.txt").mkString println(pretty(render(parse(jsonString)))) println(read[Container](jsonString)) } }
To compile the example with sbt use this project file:
import sbt._ class JSONProj(info: ProjectInfo) extends DefaultProject(info) { val json = "net.liftweb" %% "lift-json" % "2.3" }