2017-09-21 57 views
0

比方說,我必須編寫自定義Reads[Person]Person類:播放JSON:自定義讀取一個字段

import play.api.libs.functional.syntax._ 

implicit val personReads: Reads[Person] = (
    (__ \ "name").read[String] and // or ~ 
     (__ \ "age").readNullable[Int] 
    ) ((name, age) => Person(name = name, age = age)) 

它就像一個魅力,真的(無)。

但是,當json對象中只有一個字段時,我該怎麼辦?

ReadsWrites的核心是轉換這些「解析」步驟的函數語法。

以下不會編譯:

import play.api.libs.functional.syntax._ 

implicit val personReads: Reads[Person] = (
    (__ \ "name").read[String] 
    ) (name => Person(name = name)) 

你能指點該如何處理呢?

回答

1

選項1:Reads.map

import play.api.libs.json._ 

case class Person(name: String) 

object PlayJson extends App { 
    implicit val readsPeson: Reads[Person] = 
    (__ \ "name").read[String].map(name => Person(name)) 

    val rawString = """{"name": "John"}""" 
    val json = Json.parse(rawString) 
    val person = json.as[Person] 
    println(person) 
} 

選項2:Json.reads

import play.api.libs.json._ 

case class Person(name: String) 

object Person { 
    implicit val readsPerson = Json.reads[Person] 
} 

object PlayJson extends App { 
    val rawString = """{"name": "John"}""" 
    val json = Json.parse(rawString) 
    val person = json.as[Person] 
    println(person) 
} 
相關問題