读书人

how to configure spring mvc 三 to n

发布时间: 2012-10-31 14:37:32 作者: rapoo

how to configure spring mvc 3 to not return “null” object in json response?

转自:http://stackoverflow.com/questions/6049523/how-to-configure-spring-mvc-3-to-not-return-null-object-in-json-response

a sample of json response looks like this:


{"publicId":"123","status":null,"partner":null,"description":null}

?

It would be nice to truncate out all null objects in the response. In this case, the response would become

{"publicId":"123"}.


Any advice? Thanks!

?

1 Answeractive oldest votes

accepted

Yes, you can do this for individual classes by annotating them with @JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL) or you can do it across the board by configuring your ObjectMapper, setting the serialization inclusion to JsonSerialize.Inclusion.NON_NULL.

Here is some info from the Jackson FAQ: http://wiki.fasterxml.com/JacksonAnnotationSerializeNulls.

Annotating the classes is straightforward, but configuring the ObjectMapper serialization config slightly trickier. There is some specific info on doing the latter here.

?????Jackson feature: prevent serialization of nulls, default values

As of Jackson 1.1, you can suppress serialization of properties that have either:

Null value, or Default value for the bean (which may be null, or any other value after being constructed using the default constructor)

These is achieved by using one of 2 mechanisms:

Call ObjectMapper.getSerializationConfig().setSerializationInclusion() to define global setting (value enumeration JsonSerialize.Inclusion, with values ALWAYS, NON_NULL, NON_DEFAULT).

Annotate properties (i.e. serializable field or getter method that implies a property) with @JsonSerialize(include=VALUE), where value is as above.

So either:

?

  ObjectMapper mapper = new ObjectMapper();  mapper.getSerializationConfig().setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL); // no more null-valued properties

or

?

  @JsonSerialize(include=JsonSerialize.Inclusion.NON_DEFAULT)  public class MyBean {    // ... only serialize properties with values other than what they default to  }

读书人网 >JavaScript

热点推荐