2017-03-09 12 views
2
case class Foo(
    _1:Int,_2:Int,_3:Int,_4:Int,_5:Int, 
    _21:Int,_22:Int,_23:Int,_24:Int,_25:Int, 
    _31:Int,_32:Int,_33:Int,_34:Int,_35:Int, 
    _41:Int,_42:Int,_43:Int,_44:Int,_45:Int, 
    _51:Int,_52:Int,_53:Int,_54:Int,_55:Int 
) 

このようなケースクラスについては、暗黙的なjsonのde-serializerを記述する必要があります。 フィールドを分割しようとしましたが、JSONFormatがありました。しかし、私はJson.obj()を使用するために暗黙のOWritedが必要です。私もplay-json-extensionsで試しました。何か案は?22フィールド以上のケースクラスの暗黙的な書き込み方法

+0

バリュークラスを試しましたか? – FaigB

+0

バリュークラス?ごめんなさい。それを私に説明してもらえますか? – sowmiyaksr

+0

http://docs.scala-lang.org/overviews/core/value-classes.html – FaigB

答えて

1

あなたがここに探索するための3つの道は本当にあります:(。はい、定型のトン)

  1. が明示的に自分で各クラスを書き出し
  2. マクロまたはShapelessでそれを行います。
  3. すでに#2の人のライブラリを使用します。

他の誰かが私のために仕事をしているのが好きです。そのことを念頭に置いて、#3は私の好みの解決策のようです...そして、あなたは何を知っていますか?他の誰かがそれをした:play-json-derived-codecs。それはShapelessを使用しているので、任意のサイズのケースclassses、ProductNによって制約されないだけで、これらの処理することができます(スカラ座のバージョンに応じて1-22を、。)

+0

+1他の人のライブラリです。マクロを使って作業を行う[play-json-extensions](https://github.com/xdotai/play-json-extensions)もあります – vdebergue

1

我々はplay-json-extensionsを使用せずに達成することができます。私たちは以下のような22の以上のフィールドの場合クラスがあるとします。

case class Foo(
    A: Int, 
    B: Option[Int], 
    C: String, 
    D: Option[String], 
    E: Seq[String], 
    F: Date 
    more fields.. 
) 

今、私たちは分割し、グループのフィールドをいくつかのグループにおよびフォーマットを記述します。

val fooFormat1: OFormat[(Int, Option[Int], String)] = 
    ((__ \ "A").format[Long] 
     ~ (__ \ "B").format[Option[Long]] 
     ~ (__ \ "C").format[Option[Long]]).tupled 


val fooFormat2: OFormat[(Option[String], Seq[String], Date)] = 
    ((__ \ "D").format[Long] 
     ~ (__ \ "E").format[Option[Long]] 
     ~ (__ \ "F").format[Option[Long]]).tupled 

最後に、すべてのフォーマットを1つのフォーマットにマージします。

私たちは以下のような機能の構文をインポートする必要が
implicit val fooFormat: Format[Foo] = (fooFormat1 ~ fooFormat2)({ 
    case ((a, b, c), (d, e, f)) => 
     new Foo(a, b, c, d, e, f) 
    }, (foo: Foo) => ((
    foo.A, 
    foo.B, 
    foo.C 
), (
     foo.D, 
     foo.E, 
     foo.F 
    ))) 

:今

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

、遊びはオプションで、日付フィールドをデシリアライズ/シリアライズすることはできません。そこで、我々は、以下のようなオプションで、日付フィールドの暗黙のフォーマットを記述する必要があります。私たちはを書くために必要なすべてのです

implicit object DateFormat extends Format[java.util.Date] { 
    val format = new java.text.SimpleDateFormat("yyyy-MM-dd") 
    def reads(json: JsValue): JsResult[java.util.Date] = JsSuccess(format.parse(json.as[String])) 
    def writes(date: java.util.Date): JsString = JsString(format.format(date)) 
    } 

implicit def optionFormat[T: Format]: Format[Option[T]] = new Format[Option[T]] { 
    override def reads(json: JsValue): JsResult[Option[T]] = json.validateOpt[T] 

    override def writes(o: Option[T]): JsValue = o match { 
     case Some(t) => implicitly[Writes[T]].writes(t) 
     case None => JsNull 
    } 
    } 

よりフィールドよりもケースクラスのを書き込みます。

関連する問題