我有一个类,我想序列化忽略一些属性
public class User extends Model
{
static class publicView{}
@JsonView(publicView.class)
private Long id;
private String showName;
@JsonView(publicView.class)
private List<qQueue> callableQueues;
}
当我在没有JsonView的情况下序列化时,我通常会做这样的事情
public JsonNode jsonSerialization()
{
ObjectMapper mapper = new ObjectMapper();
return mapper.convertValue(this, JsonNode.class);
}
如何使用“publicView”类进行序列化?
答案 0 :(得分:6)
您可以配置对象映射器以包含publicView.class
并排除其他字段,如下所示:
MapperFeature.DEFAULT_VIEW_INCLUSION
映射器功能。ObjectMapper#getSerializationConfig().withView()
方法启用序列化视图。请参阅this page以供参考。
以下是一个例子:
public class JacksonView1 {
public static class publicView{}
public static class User {
public User(Long id, String showName, List<String> callableQueues) {
this.id = id;
this.showName = showName;
this.callableQueues = callableQueues;
}
@JsonView(publicView.class)
public final Long id;
public final String showName;
@JsonView(publicView.class)
public final List<String> callableQueues;
}
public static void main(String[] args) {
User user = new User(123l, "name", Arrays.asList("a", "b"));
ObjectMapper mapper = new ObjectMapper();
mapper.disable(MapperFeature.DEFAULT_VIEW_INCLUSION);
mapper.setConfig(mapper.getSerializationConfig()
.withView(publicView.class));
System.out.println(mapper.convertValue(user, JsonNode.class));
}
}
输出:
{"id":123,"callableQueues":["a","b"]}
答案 1 :(得分:1)
感谢Alexey Gavrilov我找到了一个解决方案,它可能不是最合适的但是有效。
public JsonNode jsonSerialization()
{
ObjectMapper mapper = new ObjectMapper();
try
{
mapper.disable(MapperFeature.DEFAULT_VIEW_INCLUSION);
return Json.parse(mapper.writerWithView(publicView.class).writeValueAsString(this));
}
catch (JsonProcessingException ex)
{
return null;
}
}