Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

json4s jackson - How to ignore field using annotations

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)
like image 273
Jae-Ung Lim Avatar asked Mar 27 '15 08:03

Jae-Ung Lim


People also ask

How do you ignore fields in Jackson?

If there are fields in Java objects that do not wish to be serialized, we can use the @JsonIgnore annotation in the Jackson library. The @JsonIgnore can be used at the field level, for ignoring fields during the serialization and deserialization.

How do you ignore a field in JSON response?

The Jackson @JsonIgnore annotation can be used to ignore a certain property or field of a Java object. The property can be ignored both when reading JSON into Java objects and when writing Java objects into JSON.

How do I ignore properties in spring boot?

Use that annotation at the top of the whole class like so: @JsonIgnoreProperties({"password"}) public class Employee { private String id; private String lastName; private String firstName; private String password; ... If you need to ignore multiple properties, separate them with a comma inside the curly braces.

How do you use JsonIgnoreProperties?

Ignoring unknown properties using @JsonIgnoreProperties If you are creating a Model class to represent the JSON in Java, then you can annotate the class with @JsonIgnoreProperties (ignoreUnknown = true) to ignore any unknown field.


2 Answers

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
like image 153
Steven Bakhtiari Avatar answered Oct 17 '22 23:10

Steven Bakhtiari


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)})
}
like image 34
S.Karthik Avatar answered Oct 17 '22 22:10

S.Karthik