OpenAPI 生成的类并对生成的类应用 JsonView
我使用 OpenAPI 来定义我的 api 和资源,并且类是自动生成的。我一直在寻找一种拥有单个模型和多个表示的方法,因此我正在研究 JsonViews 或 Filters。
有没有办法将 JsonViews 添加到生成的模型类的属性中?我一直无法弄清楚。
I'm using OpenAPI to define my api and resources and the classes are auto-generated. I've been looking for a way to have a single model and multiple representations so am looking at JsonViews or Filters.
Is there any way to add JsonViews to the properties of the generated model classes ? I haven't been able to figure it out.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我找到了一种无需修改生成的类即可达到预期行为的方法。
步骤是:
创建生成类的子类
将作为内部字段的附加属性添加到子类中
将 ObjectMapper 配置为 MapperFeature.DEFAULT_VIEW_INCLUSION = true,这意味着任何没有 JsonView 模型的属性都将包含在序列化中(默认为 false)
将 JsonView 添加到子类属性
@JsonView(Views.Private.class)
并在控制器端点添加不同的 JsonView
完成上述操作后,控制器端点将仅序列化生成模型的字段,因为它们没有 JsonView,并且子类上带有 JsonView 的字段将提醒应用程序内部。
ObjectMapper 配置的代码片段:
I've found a way to arrive to the intended behaviour without modifying the generated classes.
The steps are :
create a subclass of the generated class
add the additional properties that are to be internal fields into the subclass
configure the ObjectMapper to MapperFeature.DEFAULT_VIEW_INCLUSION = true, which means that any properties without the JsonView model will be included in Serialization (the defualt is false)
add JsonView to the subclass properties
@JsonView(Views.Private.class)
and different JsonView at the controller endpoints
With the above in place the controller endpoints will Serialise only the fields of the generated model, since they do not have the JsonView, and the fields with the JsonView on the subclass will remin internal to the application.
Code snippet of the ObjectMapper config :