play-jsonã§Reads/Writes/Formatãå®ç¾©ããªãã¦ããããã
play-jsonã¯Reads/Writes/Formatãå®ç¾©ããã®ãé¢åã¨ããè¨ãããã®ã§ãshapelessã®ç·´ç¿ãå ¼ãã¦ä½ã£ã¦ã¿ã¾ããã
https://github.com/tototoshi/play-json-generic
scala> import play.api.libs.json._ import play.api.libs.json._ scala> case class Person(firstName: String, lastName: String, friends: List[Person]) defined class Person scala> val people = Person("John", | "Lennon", | List(Person("Paul", "McCartney", Nil), | Person("George", "Harrison", Nil), | Person("Ringo", "Starr", Nil))) people: Person = Person(John,Lennon,List(Person(Paul,McCartney,List()), Person(George,Harrison,List()), Person(Ringo,Starr,List()))) scala> Json.prettyPrint(Json.toJson(people)) <console>:18: error: No Json serializer found for type Person. Try to implement an implicit Writes or Format for this type. Json.prettyPrint(Json.toJson(people)) ^
Reads/Writes/Formatãå®ç¾©ãã¦ããªãcase classãã·ãªã¢ã©ã¤ãºãããã¨ããã¨å½ç¶ãããªã¨ã©ã¼ãåºã¾ããã
import com.github.tototoshi.play.json.generic._
ãããã¨ã§ã·ãªã¢ã©ã¤ãº/ãã·ãªã¢ã©ã¤ãºã§ããããã«ãªãã¾ãã
scala> import com.github.tototoshi.play.json.generic._ import com.github.tototoshi.play.json.generic._ scala> Json.prettyPrint(Json.toJson(people)) res1: String = { "firstName" : "John", "lastName" : "Lennon", "friends" : [ { "firstName" : "Paul", "lastName" : "McCartney", "friends" : [ ] }, { "firstName" : "George", "lastName" : "Harrison", "friends" : [ ] }, { "firstName" : "Ringo", "lastName" : "Starr", "friends" : [ ] } ] } scala> Json.parse(res1).as[Person] res2: Person = Person(John,Lennon,List(Person(Paul,McCartney,List()), Person(George,Harrison,List()), Person(Ringo,Starr,List())))
play-jsonã®Json.formatã¨ãã¯ãã¯ãã§å®è£ ããã¦ããã®ã§ããã®ãã¯ãã®ããã®ãªãã·ã§ã³ã¨ãã«ã¯ä¸é¨å¯¾å¿ã§ãã¦ããªãã§ããJsonNamingã«ã¯å¯¾å¿ã§ãã¾ããã
Shapeless使ã£ã¦ã¿ããã¨ãã人ã«ã¯ The Type Astronaut's Guide to Shapeless - Underscore ããããããããããã¦ãªã¹ã¹ã¡ã§ãã
追è¨
ææããã¦æ°ã¥ãããã§ãããHListã使ã£ã¦ããã®ã§23å以ä¸ã®ãã£ã¼ã«ããæã¤case classã«ã¾ã¤ããåé¡ã解決ãã¡ãã£ã¦ã¾ããã
https://github.com/tototoshi/play-json-generic/commit/0382c149efb4ed9fd4b4bcea99841641f2ca7949