2014-10-28 75 views
1

看來你不能混用@JsonIgnore和@JsonView。我想默認隱藏一個字段,但在某些情況下顯示它。使用@JsonView來排除(如@JsonIgnore)與播放框架默認的json作家?

基本上我已經有了這個設置: -

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)呈現無child.secret和

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

到與child.secret渲染。有沒有辦法做到這一點。即有什麼方法可以將字段設置爲默認忽略,但包含在特定的JsonView中?

目前這兩個電話都包含祕密。

謝謝!

回答

1

一旦你有一個對象映射器,您可以根據您目前正在使用play.libs.Json.toJson(parent)有效地使用它以同樣的方式,和得到你想要的。

所以,無論何時你以前使用play.libs.Json.toJson(parent),只需使用new ObjectMapper().writeValueAsString(),你不會得到你的祕密。

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("")` 
+0

感謝您的支持,但我真的需要使用默認播放json映射器(play.libs.Json.toJson(父級))時不顯示機密的內容,但在使用ObjectMapper時可以顯示它。我理解我如何使用ObjectMapper手動執行它,但是這會破壞我現有的所有簡單代碼(即,我無法再使用play.libs.Json.toJson(parent))。 – Shanness 2014-10-28 12:44:26