使用@JsonView排除(如@JsonIgnore)play frameworks默认的json writer?

时间:2014-10-28 04:05:12

标签: json playframework playframework-2.0 jackson

似乎你无法混合@JsonIgnore和@JsonView。我想默认隐藏一个字段,但在某些情况下显示它。

基本上我已经有了这个设置: -

class Parent extends Model {
  public Long id;
  public Child child;
}

class Child extends Model {
  public Long id;
  @JsonView(Full.class)
  public String secret;

  public static class Full {};
}

并希望使用play.libs.Json.toJson(parent)呈现WITHOUT child.secret和

    ObjectMapper objectMapper = new ObjectMapper();
    ObjectWriter w = objectMapper.writerWithView(Child.Full.class);
    return ok(w.writeValueAsString(child));

使用child.secret进行渲染。有没有办法做到这一点。即默认情况下是否有任何方法可以将字段设置为忽略,但是包含在特定的JsonView中?

目前,两个电话都包括秘密。

谢谢!

2 个答案:

答案 0 :(得分:1)

拥有对象映射器后,您可以像使用play.libs.Json.toJson(parent)一样有效地使用它,并获得您想要的内容。

因此,无论何时使用play.libs.Json.toJson(parent),只需使用new ObjectMapper().writeValueAsString()即可获得秘密。

答案 1 :(得分:0)

您可以在您的子课程中尝试JsonFilter,您需要添加此注释@JsonFilter("myFilter")

@JsonFilter("myFilter")     // myFilter is the name of the filter, you can give your own.
class Child extends Model {

  public Long id;
  public String secret;
}

ObjectMapper mapper = new ObjectMapper();

/* Following will add filter to serialize all fields except the specified fieldname and use the same filter name which used in annotation.
   If you want to ignore multiple fields then you can pass Set<String> */

FilterProvider filterProvider = new SimpleFilterProvider().addFilter("myFilter",SimpleBeanPropertyFilter.serializeAllExcept("secret"));
mapper.setFilters(filterProvider);

try {
    String json = mapper.writeValueAsString(child);    
} catch (JsonProcessingException e) {
    Logger.error("JsonProcessingException ::: ",e);
}

If you dont want to ignore any field then, just pass empty string `SimpleBeanPropertyFilter.serializeAllExcept("")`
相关问题