json4s jackson - How to ignore field using annotations
Asked Answered
W

3

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)
Weisbrodt answered 27/3, 2015 at 8:35 Comment(1)
BEWARE: Json4s is vulnerable under DoS/DoW attacks!Trucking
C
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
Catharina answered 1/3, 2016 at 16:13 Comment(1)
how to make it work for multiple fields to be ignored?Cordie
S
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)})
}
Strange answered 27/3, 2015 at 8:42 Comment(0)
M
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

Maccaboy answered 18/8, 2020 at 18:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.