Entry 3183
scala-json-serialization
Submitted by anonymous
on Feb. 12, 2010 at 9:49 p.m.
Language: Scala. Code size: 2.0 KB.
package se.dflemstr.jsontest //I'm using the Lift JSON parser library here; there are of course alternatives... import net.liftweb.json._ import Serialization._ //Represents an event. "action" = which script to call case class Event(action: String) //Represents an attribute that a Module can have case class Attribute(maximum: Option[Double], regeneration: Option[Double], maximumMultiplier: Option[Double], regenerationMultiplier: Option[Double], bar: Option[Boolean]) //Represents a module case class Module(name: String, description: String, icon: String, power: Double, cost: Int, attributes: Option[Map[String, Attribute]], events: Option[Map[String, Event]]) //Our test application: object Main { def main(args: Array[String]) = { //The JSON we want to parse: val json = """ { "name": "Magnetic Shields", "description": "Reduces damage done to a unit", "icon": "shields", "power": 50.0, "cost": 400, "attributes": { "shields": { "bar": true, "regeneration": 200.0, "maximum": 800.0 } }, "events": { "onhit": "shields-hit" } }""" //"import" an implicit formatting rule implicit val formats = net.liftweb.json.DefaultFormats //Deserialize the JSON (aka convert the JSON into a Module object) val module = read[Module](json) for { attrs <- module.attributes //If module.attributes = Some(xyz) then store xyz in attrs (name, attribute) <- attrs //For each pair of name and attribute max <- attribute.maximum //If attribute.maximum = Some(bla) then store bla in max } println("Attribute " + name + " has a maximum of " + max) //Prints "Attribute shields has a maximum of 800.0" println(module) //Output: Module(Magnetic Shields,Reduces damage done to a unit,shields,50.0,400,Some(Map(shields -> Attribute(Some(800.0),Some(200.0),None,None,Some(true)))),None) } } // vim: set ts=4 sw=4 et:
This snippet took 0.01 seconds to highlight.
Back to the Entry List or Home.