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)
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.
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.
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.
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.
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
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)})
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With