【问题标题】:Exclude certain fields during serialization using play-json-extensions使用 play-json-extensions 在序列化期间排除某些字段
【发布时间】:2019-09-06 16:03:00
【问题描述】:

我有一个包含超过 22 个参数的案例类,为了序列化这个案例类,我正在使用 json-play-extension。

伪代码如下

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

我有一个隐含的 Foo 如下

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

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

我想要的输出如下

{
“a3” : 3,
“a4” : 4,
.
.
“a24” : 24
}

如果有任何扩展方法可以让我执行此类活动,请告诉我。任何指针都会非常有帮助。 提前谢谢!!!

【问题讨论】:

    标签: scala play-json


    【解决方案1】:

    考虑pruning多个JSON分支由andThen组成:

    (__ \ "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,
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-24
      • 2016-12-29
      相关资源
      最近更新 更多