使用play-json-extensions在序列化期间排除某些字段

时间:2019-04-16 14:02:48

标签: scala play-json

我有一个包含22个以上参数的case类,要序列化此case类,我正在使用json-play-extension。

伪代码如下

class Conversation < ApplicationRecord
  belongs_to :sender, :foreign_key => :sender_id, class_name: "Reservation"
  belongs_to :recipient, :foreign_key => :recipient_id, class_name: "Store"
  belongs_to :reservation

  has_many :messages, dependent: :destroy
end

我对Foo隐含如下

case class Foo(a1: Int,a2: Int,a3: Int,...,a24: Int)

到目前为止,我唯一的要求是简单地序列化和反序列化此case类。但是,现在我还有一个附加要求,即在序列化过程中要排除某些字段。例如,在我的输出中,我想从json输出中排除字段a1和a2。

我想要的输出如下

implicit val jsonFormat : OFormat[Foo] = Jsonx.formatCaseClass[Foo]

请让我知道是否有任何扩展方法可以让我执行此类活动。任何指针都将非常有帮助。 在此先感谢!!!

1 个答案:

答案 0 :(得分:0)

根据pruning组成来考虑andThen多个JSON分支:

(__ \ "a1" ).json.prune andThen (__ \ "a2" ).json.prune 

这是一个可行的例子

import ai.x.play.json.Jsonx
import play.api.libs.json.Json
import play.api.libs.json._

case class Foo(a1: Int, a2: Int, a3: Int, a4: Int, a5: Int, a6: Int, a7: Int, a8: Int, a9: Int, a10: Int, a11: Int, a12: Int, a13: Int, a14: Int, a15: Int, a16: Int, a17: Int, a18: Int, a19: Int, a20: Int, a21: Int, a22: Int, a23: Int, a24: Int)

object Foo {
  implicit val format = Jsonx.formatCaseClass[Foo]
}

object ExcludeFieldsFromSerialisation extends App {
  val pruneTransformation = (field: String) => (__ \ field).json.prune
  val excludedFields = List("a1", "a2").map(pruneTransformation).reduce((prune1, prune2) => prune1 andThen prune2)
  val json = Json.toJson(Foo(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24))
  val prunedJson = json.transform(excludedFields)
  println(prunedJson.get)
}

应输出

{
    "a2": 2,
    "a3": 3,
    "a4": 4,
    "a5": 5,
    "a6": 6,
    "a7": 7,
    "a8": 8,
    "a9": 9
    "a10": 10,
    "a11": 11,
    "a12": 12,
    "a13": 13,
    "a14": 14,
    "a15": 15,
    "a16": 16,
    "a17": 16,
    "a18": 18,
    "a19": 19,
    "a20": 20,
    "a21": 21,
    "a22": 22,
    "a23": 23,
    "a24": 24,
}