I have a a Map<String,Foo> foosMap
that I want to serialize through Jackson . Now I want following two settings on the serialization process:
What is the best way to achieve this ? I am using jackson-core1.9 and jackson-mapper1.9 jars in my project.
my solution, hope help
custom ObjectMapper and config to spring xml(register message conveters)
public class PyResponseConfigObjectMapper extends ObjectMapper {
public PyResponseConfigObjectMapper() {
disable(SerializationFeature.WRITE_NULL_MAP_VALUES); //map no_null
setSerializationInclusion(JsonInclude.Include.NON_NULL); // bean no_null
}
}
Answer seems to be a little old, What I did was to use this mapper to convert a MAP
ObjectMapper mapper = new ObjectMapper().configure(SerializationConfig.Feature.WRITE_NULL_MAP_VALUES, false);
a simple Map
:
Map<String, Object> user = new HashMap<String,Object>(); user.put( "id", teklif.getAccount().getId() ); user.put( "fname", teklif.getAccount().getFname()); user.put( "lname", teklif.getAccount().getLname()); user.put( "email", teklif.getAccount().getEmail()); user.put( "test", null);
Use it like this for example:
String json = mapper.writeValueAsString(user);
For Jackson versions < 2.0 use this annotation on the class being serialized:
@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)
Source: Stackoverflow.com