Skip to content

Instantly share code, notes, and snippets.

@kajstrom
Last active July 15, 2017 16:09
Show Gist options
  • Save kajstrom/27fa9ac6d20af4ea07227326e101446e to your computer and use it in GitHub Desktop.
Save kajstrom/27fa9ac6d20af4ea07227326e101446e to your computer and use it in GitHub Desktop.
name := """minimal-scala"""
version := "1.0"
scalaVersion := "2.11.7"
libraryDependencies += "com.typesafe.play" %% "play-json" % "2.5.13"
object InventoryItem {
implicit val inventoryItemWrites: Writes[InventoryItem] = (
(JsPath \ "name").write[String] and
(JsPath \ "serialNumber").write[String] and
(JsPath \ "value").write[Float]
)(unlift(InventoryItem.unapply))
implicit val inventoryItemReads: Reads[InventoryItem] = (
(JsPath \ "name").read[String] and
(JsPath \ "serialNumber").read[String] and
(JsPath \ "value").read[Float]
)(InventoryItem.apply _)
}
case class InventoryItem(name: String, serialNumber: String, value: Float) {}
object ReadingJson extends App {
var inventory: List[InventoryItem] = List()
val itemJsonString = Source.fromFile("D:\\Path\\To\\My.json").mkString
val json = Json.parse(itemJsonString)
json.validate[List[InventoryItem]] match {
case s: JsSuccess[List[InventoryItem]] => inventory = s.get
case e: JsError => println("Oh dog, what done")
}
}
[
{
"name": "Item",
"serialNumber": "asdsad",
"value": 22
},
{
"name": "Another Item",
"serialNumber": "SRS-001",
"value": 33
}
]
object WritingJson extends App {
var inventory = List[InventoryItem]()
inventory = inventory :+ InventoryItem("Name", "SR-001", 33.0)
val json = Json.toJson(inventory)
println(Json.stringify(json))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment