[英]Avoid serialization of certain fields at runtime in Jackson
我有一个生成JSON的控制器,然后从该控制器返回一个实体对象,该对象将由Jackson自动序列化。
现在,我想避免基于传递给控制器的参数返回某些字段。 我查看了使用FilterProperties / Mixins等完成此操作的示例。但是我看到的所有示例都要求我使用ObjectMapper手动序列化/反序列化Bean。 没有手动序列化,有没有办法做到这一点? 我拥有的代码与此类似:
@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
}
现在,基于传递给控制器的“变量”的值,我想显示/隐藏MyEntity的col2。 而且我不想手动对类进行序列化/反序列化。 有什么办法吗? 我是否可以根据“变量”的值从外部更改Mapper Jackson用来序列化类的类?
将JsonView与MappingJacksonValue结合使用。
考虑以下示例:
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 ...
}
然后在Spring MVC控制器中:
@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;
}
使用此注释并将值设置为null,它将不会被序列化:
@JsonInclude(Include.NON_NULL)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.