是否可以要求在 jax-rs (jersey+moxy) JSON 序列化中显式包含对象的字段,而不是@JsonbIgnore?



我有一个实现接口的JPA实体,我想通过jax-rs端点只公开由该接口定义的字段。看起来像:

public interface ConnectedAppExternal {

String getId();
String getName();
}
@Entity(name="connected_application")
public class ConnectedApp implements ConnectedAppExternal {
@Id
@Column(name="id")
private id;
@Column(name="name")
private String name;
@Column(name="internal_status")
private String internalStatus;
...
@Override
public String getId(){
return this.id;
}
@Override
public String getName(){
return this.name;
}
public String getInternalStatus(){
return this.internalStatus;
}
public void setId(String id){
this.id = id;
}
public void setName(String name){
this.name = name;
}
public void setInternalStatus(String internalStatus){
this.internalStatus= internalStatus;
}
...

}
@Path("/applications")
public class ConnectedAppResource {
@Inject
ConnectedAppService appService;
...
@GET("applications/{id}")
@Produces("application/json")
public ConnectedAppExternal getConnectedApplication(@PathParam("id") String id){
return appService.getAppById(id);
}
...
}

即使我使我的jax-rs资源@GET方法返回ConnectedAppExternal响应,Moxy将序列化整个JPA实体与所有它的属性,所以我最终不得不添加@JsonbIgnore到每个新的内部实体字段,我不想暴露;或者定义一个只包含公开接口字段的DTO,这意味着大量的映射和对齐开销(更多代码=>更多bug/意外泄漏)。

  • 所以:是否有一个简单的方法,我可以使Moxy序列化这些ConnectedAppExternal接口定义的属性?(也许是我在研究https://www.eclipse.org/eclipselink/documentation/3.0/moxy/json.htm#sthref204上的文档并遵循序列化器流时遗漏的Moxy编组器/解组器配置设置?)

(我很确定没有,因为我已经看到了序列化器代码,但只是要求一个替代的工作方式,无论如何;)

,可能至少避免要求显式@JsonbIgnore/@JsonbTransient排除非暴露的字段,因为Moxy默认情况下用getter/setter序列化每个字段,而则要求显式@JsonbProperty包含JSON序列化/暴露的字段?

作为一种方法,您可以声明带有所需数据的JPA投影查询,并返回Map<String,>从您的资源中键入。像这样:

@NamedQueries({
@NamedQuery(name="ConnectedApp.findByName",
query="SELECT c.id, c.internalStatus FROM ConnectedApp c WHERE c.name = :name")
}) 

参见:https://dzone.com/articles/projection-queries-a-way-to-optimize-data-traffic或https://www.objectdb.com/java/jpa/query/named

另一种方法是只序列化Jsonb所需的属性,有点像这样:

@GET
@Path("applications/{id}")
@Produces(MediaType.APPLICATION_JSON)
public String getApp(@PathParam("id") String id) {
JsonbConfig config = new JsonbConfig().withPropertyVisibilityStrategy(
new PropertyVisibilityStrategy(){
@Override
public boolean isVisible(Field field) {
return List.of("id", "name").indexOf(field.getName()) != -1;
}
@Override
public boolean isVisible(Method method) {
return false;
}

});
Jsonb jsonb = JsonbBuilder.newBuilder().withConfig(config).build();
return jsonb.toJson(appService.getAppById(id));
}

请在这里找到示例:https://adambien.blog/roller/abien/entry/private_fields_serialization_with_json