[英]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.