我有一个生成 JSON 的 Controller ,从该 Controller 中,我返回一个实体对象,该对象由 Jackson 自动序列化。
现在,我想避免根据传递给 Controller 的参数返回一些字段。我查看了使用 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
}
现在,根据传递给 Controller 的“变量”的值,我想显示/隐藏 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 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;
}
关于java - 避免在 Jackson 中运行时序列化某些字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39903846/