简体   繁体   English

如何在Java Play Framework 2.5.x中从同一模型呈现不同的JSON?

[英]How to render different JSONs from the same model in Java Play Framework 2.5.x?

I have a model (entity bean) Bank Accounts with 4 fields: 我有一个具有4个字段的模型(实体Bean)银行帐户:

  1. Account Number. 帐号。
  2. Account Holder's Name. 账户持有人名称。
  3. CustomerID 顾客ID
  4. GroupID 组号

I have two different controllers that render the Account Number and Account Holder's Name in one view, and the CustomerID and GroupID in another view. 我有两个不同的控制器,它们在一个视图中呈现“帐号”和“帐户持有人的姓名”,在另一视图中呈现“ CustomerID”和“ GroupID”。 But, when using Json.toJson(bankAccountObject) in my views, it returns all four fields including the null values. 但是,当在我的视图中使用Json.toJson(bankAccountObject)时,它将返回所有四个字段,包括空值。 I cannot annotate these with @JsonIgnore because if I do it for one set of fields for one view the same becomes invisible to the other view. 我无法使用@JsonIgnore注释这些,因为如果对一个视图的一组字段执行此操作,则对另一个视图而言,该字段将变得不可见。 What would be the best way to selectively render model fields in my views and not show the null values? 在我的视图中有选择地呈现模型字段而不显示空值的最佳方法是什么?

Use Jackson's JsonView annotation as explained here: 使用Jackson的JsonView注释,如下所示:

http://www.baeldung.com/jackson-json-view-annotation http://www.baeldung.com/jackson-json-view-annotation

And to ignore null values: 并忽略空值:

http://www.baeldung.com/jackson-ignore-null-fields http://www.baeldung.com/jackson-ignore-null-fields

But, keep in mind that if you want to heavily customized Jackson's ObjectMapper instantiation (for example to do something like mapper.disable(MapperFeature.DEFAULT_VIEW_INCLUSION) ), then you need to disable the default one and create your own, as explained here: 但是,请记住,如果要大量自定义Jackson的ObjectMapper实例化(例如,执行诸如mapper.disable(MapperFeature.DEFAULT_VIEW_INCLUSION) ),则需要禁用默认实例并创建自己的实例,如下所述:

https://www.playframework.com/documentation/2.5.x/JavaJsonActions#Advanced-usage https://www.playframework.com/documentation/2.5.x/JavaJsonActions#Advanced-usage

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM