Advertisement
Guest User

Untitled

a guest
Apr 17th, 2014
51
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.29 KB | None | 0 0
  1. val json: JsValue = Json.parse("""
  2. {
  3. "item": {
  4. "id" : "11111111",
  5. "name" : "box",
  6. "categories" : [{
  7. "name" : "blue box",
  8. "id" : "12345",
  9. },
  10. {
  11. "name" : "fancy box",
  12. "id" : "98765",
  13. }]
  14. }
  15. }
  16. """)
  17.  
  18. //I define my class and reader for one category
  19. case class ItemCategory(id: Option[String], name: String)
  20. implicit val categoryRead: Reads[ItemCategory] = (
  21. (JsPath "item" "categories" "id").readNullable[String] and
  22. (JsPath "item" "categories" "name").read[String]
  23. )(ItemCategory.apply _)
  24.  
  25. //I define my class and reader for one item
  26. case class MyItem(categories : Option[List[ItemCategory]], id : Option[String], name : Option[String])
  27. implicit val myItemRead: Reads[MyItem] = (
  28. (JsPath "item" "categories").readNullable[List[ItemCategory]] and
  29. (JsPath "item" "id").readNullable[String] and
  30. (JsPath "item" "name").readNullable[String]
  31. )(MyItem.apply _)
  32.  
  33. //I then try to read :
  34. var item: JsResult[MyItem] = json.validate[MyItem](myItemRead)
  35. println(item)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement