Reputation: 3038
I have a controller which produces JSON, and from this controller, I return an entity object, which is automatically serialized by Jackson.
Now, I want to avoid returning some fields based on a parameter passed to the controller. I looked at examples where this is done using FilterProperties / Mixins etc. But all the examples I saw requires me to use ObjectMapper to serialize / de-serialize the bean manually. Is there any way to do this without manual serialization? The code I have is similar to this:
@RestController
@RequestMapping(value = "/myapi", produces = MediaType.APPLICATION_JSON_VALUE)
public class MyController {
@Autowired
private MyService myService;
@RequestMapping(value = "/test/{variable}",method=RequestMethod.GET)
public MyEntity getMyEntity(@PathVariable("variable") String variable){
return myservice.getEntity(variable);
}
}
@Service("myservice")
public class MyService {
@Autowired
private MyEntityRepository myEntityRepository;
public MyEntity getEntity(String variable){
return myEntityRepository.findOne(1L);
}
}
@Entity
@Table(name="my_table")
@JsonIgnoreProperties(ignoreUnknown = true)
public class MyEntity implements Serializable {
@Column(name="col_1")
@JsonProperty("col_1")
private String col1;
@Column(name="col_2")
@JsonProperty("col_2")
private String col2;
// getter and setters
}
Now, based on the value of "variable" passed to the controller, I want to show/hide col2 of MyEntity. And I do not want to serialize/deserialize the class manually. Is there any way to do this? Can I externally change the Mapper Jackson uses to serialize the class based on the value of "variable"?
Upvotes: 0
Views: 803
Reputation: 12932
Use JsonView in conjunction with MappingJacksonValue.
Consider following example:
class Person {
public static class Full {
}
public static class OnlyName {
}
@JsonView({OnlyName.class, Full.class})
private String name;
@JsonView(Full.class)
private int age;
// constructor, getters ...
}
and then in Spring MVC controller:
@RequestMapping("/")
MappingJacksonValue person(@RequestParam String view) {
MappingJacksonValue value = new MappingJacksonValue(new Person("John Doe", 44));
value.setSerializationView("onlyName".equals(view) ? Person.OnlyName.class : Person.Full.class);
return value;
}
Upvotes: 1
Reputation: 2542
Use this annotation and set the value to null, it will not be serialised:
@JsonInclude(Include.NON_NULL)
Upvotes: -1