如果您希望过滤器工作,您似乎必须添加一个注释,指示在对 bean 类进行序列化时使用哪个过滤器:
@JsonFilter("test")
public class Data {
public String data1 = "value1";
public String data2 = "value2";
}
编辑
OP刚刚添加了一个注释,只是回答不使用bean动画,然后如果您要导出的字段数量非常少,您可以检索该数据并自己构建一个列表地图,那里似乎没有其他方法可以做到这一点。
Map<String, Object> map = new HashMap<String, Object>();
map.put("data1", obj.getData1());
...
// do the serilization on the map object just created.
如果您想排除特定字段并保留最多字段,也许您可以使用反射来做到这一点。以下是我编写的将 bean 传输到地图的方法,您可以更改代码以满足自己的需要:
protected Map<String, Object> transBean2Map(Object beanObj){
if(beanObj == null){
return null;
}
Map<String, Object> map = new HashMap<String, Object>();
try {
BeanInfo beanInfo = Introspector.getBeanInfo(beanObj.getClass());
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor property : propertyDescriptors) {
String key = property.getName();
if (!key.equals("class")
&& !key.endsWith("Entity")
&& !key.endsWith("Entities")
&& !key.endsWith("LazyInitializer")
&& !key.equals("handler")) {
Method getter = property.getReadMethod();
if(key.endsWith("List")){
Annotation[] annotations = getter.getAnnotations();
for(Annotation annotation : annotations){
if(annotation instanceof javax.persistence.OneToMany){
if(((javax.persistence.OneToMany)annotation).fetch().equals(FetchType.EAGER)){
List entityList = (List) getter.invoke(beanObj);
List<Map<String, Object>> dataList = new ArrayList<>();
for(Object childEntity: entityList){
dataList.add(transBean2Map(childEntity));
}
map.put(key,dataList);
}
}
}
continue;
}
Object value = getter.invoke(beanObj);
map.put(key, value);
}
}
} catch (Exception e) {
Logger.getAnonymousLogger().log(Level.SEVERE,"transBean2Map Error " + e);
}
return map;
}
但我建议你使用Google Gson 作为 JSON 反序列化器/序列化器,主要原因是我讨厌处理异常的东西,它只是弄乱了编码风格。
利用 bean 类上的版本控制注释很容易满足您的需求,如下所示:
@Since(GifMiaoMacro.GSON_SENSITIVE) //mark the field as sensitive data and will not export to JSON
private boolean firstFrameStored; // won't export this field to JSON.
您可以像这样定义宏是导出还是隐藏字段:
public static final double GSON_SENSITIVE = 2.0f;
public static final double GSON_INSENSITIVE = 1.0f;
默认情况下,Gson 会导出所有未被@Since 注释的字段,因此如果您不关心该字段,则无需执行任何操作,它只是导出该字段。
如果您不想导出到 json 的某些字段,即敏感信息,只需向该字段添加注释。并用这个生成json字符串:
private static Gson gsonInsensitive = new GsonBuilder()
.registerTypeAdapter(ObjectId.class,new ObjectIdSerializer()) // you can omit this line and the following line if you are not using mongodb
.registerTypeAdapter(ObjectId.class, new ObjectIdDeserializer()) //you can omit this
.setVersion(GifMiaoMacro.GSON_INSENSITIVE)
.disableHtmlEscaping()
.create();
public static String toInsensitiveJson(Object o){
return gsonInsensitive.toJson(o);
}
那就用这个吧:
String jsonStr = StringUtils.toInsensitiveJson(yourObj);
由于 Gson 是无状态的,所以使用静态方法来完成你的工作就可以了,我用 Java 尝试了很多 JSON 序列化/反序列化框架,但发现 Gson 在性能和易用性方面都非常出色。