tags:

views:

302

answers:

3

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
A: 

I don't see any way of doing that. If you need to dynamically decide which properties are marshalled, then I suggest you manually construct a Map of keys to values for your objects, and then pass that Map to Jackson, rather than passing the User object directly.

skaffman
thanks. I think the Map pattern is a little weak too, when it comes to creating JSON arrays.Map<String,Object> map1 = new HashMap<String,Object>();map1.put("fname", "Steve");map1.put("lname", "Colly"); Map<String,Object> map2 = new HashMap<String,Object>();map2.put("fname", "Josh");map2.put("lname", "Roff");List jsonArray = new ArrayList();jsonArray.add(map1);jsonArray.add(map2);new ObjectMapper().writeValueAsString(jsonArray) ...does not produce???[{'fname':'Steve','lname':'Colly'},{'fname':'Josh','lname':'Roff'}]
@kapil.isr: Yes it does, I just tried it, it works fine. The order of the keys is different, but that's because you used a `HashMap` rather than a `LinkedHashMap`.
skaffman
o yeah it works, sorry typo :) thanks a lot!!
Also do you know if ObjectMapper can be shared among threads, i know doc says it can. But I just wanted to make sure, if thats the case. There doesn't seem to be whole lot of information on jackson out there, their own doc seems limited.
`ObjectMapper` can be shared, yes.
skaffman
I am not quite sure why you would doubt explicit guarantee by author(s) of the library (I assume you refer to http://wiki.fasterxml.com/JacksonFAQ, "Is ObjectMapper thread-safe? "), but yes, it is fully shareable as long as you do not try changing configuration settings when sharing.
StaxMan
+1  A: 

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.

Toader Mihai Claudiu
A: 

Have you tried using JSON Views? Views allow annotation-based mechanism for defining different profiles, so if you just need slightly differing views for different users, this could work for you.

StaxMan