Last active
July 26, 2017 15:06
-
-
Save propensive/6479269 to your computer and use it in GitHub Desktop.
Example of automatic case class extraction from JSON using Rapture JSON 0.9.2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Welcome to Scala version 2.10.2 (Java HotSpot(TM) 64-Bit Server VM, Java 1.6.0_24). | |
Type in expressions to have them evaluated. | |
Type :help for more information. | |
scala> import rapture.core._ | |
import rapture.core._ | |
scala> import rapture.json._ | |
import rapture.json._ | |
scala> import jsonParsers.scalaJson._ // in Rapture JSON 0.10, import jsonBackends.scalaJson._ | |
import jsonParsers.scalaJson._ | |
scala> import strategy.throwExceptions // not required in Rapture JSON 0.10 | |
import strategy.throwExceptions | |
scala> val molecule = json""" | |
| { | |
| "name": "Sodium bicarbonate", | |
| "elements": [ | |
| { "name": "Hydrogen", "count": 1, "unitMass": 1.00794 }, | |
| { "name": "Carbon", "count": 1, "unitMass": 12.0107 }, | |
| { "name": "Oxygen", "count": 3, "unitMass": 15.9994 }, | |
| { "name": "Sodium", "count": 1, "unitMass": 22.989769 } | |
| ] | |
| } | |
| """ | |
molecule: rapture.io.Json = | |
{ | |
"name": "Sodium bicarbonate", | |
"elements": [ | |
{ | |
"name": "Hydrogen", | |
"count": 1.0, | |
"unitMass": 1.00794 | |
}, | |
{ | |
"name": "Carbon", | |
"count": 1.0, | |
"unitMass": 12.0107 | |
}, | |
{ | |
"name": "Oxygen", | |
"count": 3.0, | |
"unitMass": 15.9994 | |
}, | |
{ | |
"name": "Sodium", | |
"count": 1.0, | |
"unitMass": 22.989769 | |
} | |
] | |
} | |
scala> case class Element(name: String, count: Int, unitMass: Double) | |
defined class Element | |
scala> molecule.elements(1).as[Element] | |
res0: Element = Element(Carbon,1,12.0107) | |
scala> case class Molecule(name: String, elements: List[Element]) { def mass = elements.map(c => c.count*c.unitMass).sum } | |
defined class Molecule | |
scala> molecule.as[Molecule] | |
res1: Molecule = Molecule(Sodium bicarbonate,List(Element(Hydrogen,1,1.00794), Element(Carbon,1,12.0107), Element(Oxygen,3,15.9994), Element(Sodium,1,22.989769))) | |
scala> res1.mass | |
res2: Double = 84.006609 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment