根据我认为是官方用户指南的http://json-b.net/users-guide.html,引擎应该序列化它找到的任何属性,不管有没有bean访问器方法(我知道Dog示例使用了公共字段,但请参阅Person示例中的私有字段)。
给定这些类:
public class Rectangle {
private double length1 = 0.0;
@JsonbProperty("length2")
private double length2 = 0.0;
public double width = 0.0;
}
public class Rectangle2 {
@JsonbProperty
private double length = 0.0;
private double width = 0.0;
public double getLength() {
return length;
}
public double getWidth() {
return width;
}
}当我像这样序列化它时:
public class App2 {
public static void main(String... argv) {
Jsonb jsonb = JsonbBuilder.create();
System.out.println("Rectangle: " + jsonb.toJson(new Rectangle()));
System.out.println("Rectangle2: " + jsonb.toJson(new Rectangle2()));
}
}输出是这样的:
Rectangle: {"width":0.0}
Rectangle2: {"length":0.0,"width":0.0}我看到的是,在矩形中,只有宽度是序列化的,因为它是公共的。length1和length2被忽略,因为它们是私有的,即使length2上有属性注释也是如此。Rectangle2是完全序列化的,因为它有bean方法。
一定要这样吗?要求我将所有字段都设置为公共和可变的以启用序列化似乎是一个巨大的限制。
我的依赖项设置如下:
<dependency>
<groupId>javax.json.bind</groupId>
<artifactId>javax.json.bind-api</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>org.eclipse</groupId>
<artifactId>yasson</artifactId>
<version>1.0.2</version>
</dependency>
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.json</artifactId>
<version>1.1.4</version>
</dependency>发布于 2019-02-06 23:15:18
我在yasson源(org.eclipse.yasson.internal.model.PropertyValuePropagation.DefaultVisibilityStrategy):中找到了关于规范和字段可见性的参考资料
@Override
public boolean isVisible(Field field) {
//don't check field if getter is not visible (forced by spec)
if (method != null && !isVisible(method)) {
return false;
}
return Modifier.isPublic(field.getModifiers());
}我不能对规范说话,但这与我所看到的-字段将只根据getter方法的可见性进行序列化。
我希望我的序列化只由字段驱动,而只有我想序列化的字段-所以我使用了一个定制的PropertyVisibilityStrategy,它不公开任何方法,只公开带有JsonbProperty注释的字段。这让我得到了我想要的大部分东西:
Jsonb jsonb = JsonbBuilder.newBuilder().withConfig(
new JsonbConfig().withPropertyVisibilityStrategy(new PropertyVisibilityStrategy() {
@Override
public boolean isVisible(Field field) {
return field.getAnnotation(JsonbProperty.class) != null;
}
@Override
public boolean isVisible(Method method) {
return false;
}
})
).build();https://stackoverflow.com/questions/54555288
复制相似问题