2

I have a case class that is having more than 22 parameters and to serialize this case class I am using json-play-extension.

Pseudo code is as follows

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

I have an implicit for Foo as follows

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

Till now, my only requirement was to simply serialize and deserialize this case class. However, now I have an additional requirement to exclude certain fields during serialization. For example, in my output I want to exclude fields a1 and a2 from the json output.

My desired output is as follows

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

Please let me know if there are any extension method that will allow me to perform such activity. Any pointers will be highly helpful. Thanks in advance !!!

Chaitanya Waikar
  • 2,686
  • 8
  • 26

1 Answers1

0

Consider pruning multiple JSON branches by andThen composition:

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

Here is a working example

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)
}

which should output

{
    "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,
}
Mario Galic
  • 41,266
  • 6
  • 39
  • 76