5

I`m using json4s-jackson(version 3.2.11).

I'm trying to ignore field using annotations(like jackson java version).

Here's exmaple:

case class User(id: Long, name: String, accessToken: String)

Following code is not working.

@JsonIgnoreProperties(Array("accessToken"))
case class User(id: Long, name: String, @JsonProperty("accessToken") accessToken: String)
kaya3
  • 47,440
  • 4
  • 68
  • 97
Jae-Ung Lim
  • 93
  • 1
  • 4
  • BEWARE: Json4s is [vulnerable under DoS/DoW attacks](https://github.com/json4s/json4s/issues?utf8=%E2%9C%93&q=is%3Aissue+is%3Aopen+denial)! – Andriy Plokhotnyuk Aug 22 '20 at 07:48

3 Answers3

9

In json4s you can provide an instance of a field serialiser which can be configured to ignore or rename fields. Check the docs for more detail, but something like the following should work:

case class User(id: Long, name: String, accessToken: String)

val userSerializer = FieldSerializer[User](
  FieldSerializer.ignore("accessToken")
)

implicit val formats = DefaultFormats + userSerializer
Steven Bakhtiari
  • 3,227
  • 2
  • 20
  • 24
1

You can write a utility method, with Keys to remove as default parameter like this,

def removeKeys(entity:AnyRef, keys: List[String]=List("accessToken", "key1", "key2")): String= {
compact(Extraction.decompose(entity).removeField { x => keys.contains(x._1)})
}
S.Karthik
  • 1,389
  • 9
  • 21
0

Extending Steven Bakhtari's answer: if you want to ignore multiple fields you can do this:

FieldSerializer.ignore("config") orElse ignore("category")

as explained in this https://github.com/json4s/json4s/issues/90 issue