Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jackson - suppressing serialization(write) of properties dynamically

Tags:

java

json

jackson

I am trying to convert java object to JSON object in Tomcat/jersey using Jackson. And want to suppress serialization(write) of certain properties dynamically.

I can use JsonIgnore, but I want to make the ignore decision at runtime. Any ideas??

So as an example below, I want to suppress "id" field when i serialize the User object to JSON..

new ObjectMapper.writeValueAsString(user);


class User {

private String id = null;
private String firstName = null;
private String lastName = null;

//getters
//setters

}//end class
like image 660
kapso Avatar asked Jun 05 '10 17:06

kapso


2 Answers

Yes, JSON View is the way to go.

If you e.g. need to let the client to decide which fields to marshal, this example might help: http://svn.codehaus.org/jackson/tags/1.6/1.6.3/src/sample/CustomSerializationView.java

like image 186
dean Avatar answered Oct 16 '22 12:10

dean


Check

ObjectMapper.configure(SerialiationJson.Feature f, boolean value)

and

org.codehaus.jackson.annotate.JsonIgnore 

annotation

This will work only when you want all instances of a certain type to ignore id on serialization. If you truly want dynamic (aka per instance customization) you will probabily have to hack the jackson library yourself.

like image 40
Mihai Toader Avatar answered Oct 16 '22 11:10

Mihai Toader