简体   繁体   中英

Do not serialize subtype properties with Jackson in Spring MVC 3

I am using Spring MVC with a controller like this:

@RequestMapping(value = "/list", method = RequestMethod.GET, produces = "application/json")
public @ResponseBody List<Service> list() {
return services.list();
}

The model is like this:

public class Service {
 private User user;
 ...
}

public class User {
 private String name;
 ...
}

public class ExtendedUser extends User {
 private Location location;
 ...
}

For sure, an object of type ExtendedUser is created in the application and set in Service. When the controller /list answer the request, an object of type ExtendedUser is serialized despite the reference in Service class is User. I would like to know if there is some way with annotations to only serialize supertype (the referenced type) and avoid the subtype propierties.

Taking the example into account, I want a JSON without the location property to be returned.

Thanks in advance

在ExtendedUser上尝试@JsonInclude(Include.NON_NULL)

Your statement of "I want a JSON without the location property to be returned" can easily be accomplished using the @JsonIngore annotation:

public class ExtendedUser extends User {
    @JsonIgnore
    private Location location;
     ...
}

Is that what you're trying to do, though, just eliminate the location from the response, or does the actual type returned (type id) matter? If I'm off base, please post your expected JSON result and your actual JSON result.

I think this will do the trick:

@JsonSerialize(using=User.class)

See this related answer: https://stackoverflow.com/a/13926740/1292605

I recommend to use as property of @JsonSerialize. BTW, @JsonSerialize can be declared on the fields so that it will not impact the common behavior of serialization of User or ExtendedUser .

public class Service {
  @JsonSerialize(as = User.class)
  private User user;
  ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM