2017-09-01 61 views
0

我有一個Scala的應用程序,有一個案例類像 -通用播放JSON格式器

case class SR(
    systemId: Option[String] = None, 
    x: Map[Timestamp, CaseClass1] = Map.empty, 
    y: Map[Timestamp, CaseClass2] = Map.empty, 
    y: Map[Timestamp, CaseClass3] = Map.empty 
) 

現在我必須提供一個隱含的讀取和寫入JSON格式的屬性X,Y,Z爲SR案例類像 -

implicit val mapCMPFormat = new Format[Map[Timestamp, CaseClass1]] { 
    def writes(obj: Map[Timestamp, CaseClass1]): JsValue = 
     JsArray(obj.values.toSeq.map(Json.toJson(_))) 
    def reads(jv: JsValue): JsResult[Map[Timestamp, CaseClass1]] = jv.validate[scala.collection.Seq[CaseClass1]] match { 
     case JsSuccess(objs, path) => JsSuccess(objs.map(obj => obj.dataDate.get -> obj).toMap, path) 
     case err: JsError => err 
    } 
    } 

等等類似的Y和Z,並且在將來,我會加入像X,Y,Z在SR案例類更多的屬性,然後需要提供formators。

因此,我可以得到一些將照顧所有類型的通用Formater?

+0

什麼這個問題之前已經嘗試過? – cchantep

回答

1

據我所知,一個簡單的方法來做到這一點並不存在,但是,要創建一個「默認」的讀者爲每個對象不應該是很難做到的,是這樣的:

case class VehicleColorForAdd(
    name: String, 
    rgb: String 
) 

object VehicleColorForAdd { 
    implicit val jsonFormat: Format[VehicleColorForAdd] = Json.formats[VehicleColorForAdd] 
} 

這樣你有通過簡單地使用對象訪問隱式的,所以你可以有一個包含有沒有問題,此對象的其它對象:

case class BiggerModel(
    vehicleColorForAdd: VehicleColorForAdd 
) 

object BiggerModel{ 
    implicit val jsonFormat: Format[BiggerModel] = Json.format[BiggerModel] 
} 

可悲的是,你需要爲每個類類型做到這一點,但你可以在「擴展」玩你自己的轉換器,例如,這是我的一些默認閱讀器:

package common.json 

import core.order.Order 
import org.joda.time.{ DateTime, LocalDateTime } 
import org.joda.time.format.DateTimeFormat 
import core.promotion.{ DailySchedule, Period } 
import play.api.libs.functional.syntax._ 
import play.api.libs.json.Reads._ 
import play.api.libs.json._ 
import play.api.libs.json.{ JsError, JsPath, JsSuccess, Reads } 

import scala.language.implicitConversions 

/** 
* General JSon readers and transformations. 
*/ 
object JsonReaders { 

    val dateTimeFormat = "yyyy-MM-dd HH:mm:ss" 

    class JsPathHelper(val path: JsPath) { 
    def readTrimmedString(implicit r: Reads[String]): Reads[String] = Reads.at[String](path)(r).map(_.trim) 

    def readUpperString(implicit r: Reads[String]): Reads[String] = Reads.at[String](path)(r).map(_.toUpperCase) 

    def readNullableTrimmedString(implicit r: Reads[String]): Reads[Option[String]] = Reads.nullable[String](path)(r).map(_.map(_.trim)) 
    } 

    implicit val localDateTimeReader: Reads[LocalDateTime] = Reads[LocalDateTime]((js: JsValue) => 
    js.validate[String].map[LocalDateTime](dtString => 
     LocalDateTime.parse(dtString, DateTimeFormat.forPattern(dateTimeFormat)))) 

    val localDateTimeWriter: Writes[LocalDateTime] = new Writes[LocalDateTime] { 
    def writes(d: LocalDateTime): JsValue = JsString(d.toString(dateTimeFormat)) 
    } 

    implicit val localDateTimeFormat: Format[LocalDateTime] = Format(localDateTimeReader, localDateTimeWriter) 

    implicit val dateTimeReader: Reads[DateTime] = Reads[DateTime]((js: JsValue) => 
    js.validate[String].map[DateTime](dtString => 
     DateTime.parse(dtString, DateTimeFormat.forPattern(dateTimeFormat)))) 

    implicit def toJsPathHelper(path: JsPath): JsPathHelper = new JsPathHelper(path) 

    val defaultStringMax: Reads[String] = maxLength[String](255) 

    val defaultStringMinMax: Reads[String] = minLength[String](1) andKeep defaultStringMax 

    val rgbRegex: Reads[String] = pattern("""^#([\da-fA-F]{2})([\da-fA-F]{2})([\da-fA-F]{2})$""".r, "error.invalidRGBPattern") 

    val plateRegex: Reads[String] = pattern("""^[\d\a-zA-Z]*$""".r, "error.invalidPlatePattern") 

    val minOnlyWordsRegex: Reads[String] = minLength[String](2) keepAnd onlyWordsRegex 

    val positiveInt: Reads[Int] = min[Int](1) 

    val zeroPositiveInt: Reads[Int] = min[Int](0) 

    val zeroPositiveBigDecimal: Reads[BigDecimal] = min[BigDecimal](0) 

    val positiveBigDecimal: Reads[BigDecimal] = min[BigDecimal](1) 

    def validLocalDatePeriod()(implicit reads: Reads[Period]) = 
    Reads[Period](js => reads.reads(js).flatMap { o => 
     if (o.startPeriod isAfter o.endPeriod) 
     JsError("error.startPeriodAfterEndPeriod") 
     else 
     JsSuccess(o) 
    }) 

    def validLocalTimePeriod()(implicit reads: Reads[DailySchedule]) = 
    Reads[DailySchedule](js => reads.reads(js).flatMap { o => 
     if (o.dailyStart isAfter o.dailyEnd) 
     JsError("error.dailyStartAfterDailyEnd") 
     else 
     JsSuccess(o) 
    }) 
} 

然後,您只需要輸入這個對象來訪問所有的這種隱含轉換器:

package common.forms 

import common.json.JsonReaders._ 
import play.api.libs.json._ 

/** 
* Form to add a model with only one string field. 
*/ 
object SimpleCatalogAdd { 

    case class Data(
    name: String 
) 

    implicit val dataReads: Reads[Data] = (__ \ "name").readTrimmedString(defaultStringMinMax).map(Data.apply) 
} 
+0

是的,我已經這樣做了,但它仍然需要格式爲Map [Timestamp,CaseClass1]。 –

+0

Editer我的回答是,希望這個例子能夠很好地工作,給你一個關於如何實現Map讀者或作者的想法,更多信息請參見https://stackoverflow.com/questions/20029412/scala-play-parse-json-into-地圖 - INSTEAD-OF-jsobject – rekiem87