java在序列化时向JSON添加自定义元素
我有几个JPA实体,比如
public class Person implements Serializable
{
@Id
private long id;
@OneToMany(mappedBy = "Person", fetch = FetchType.LAZY)
private List<Adresse> adressen;
@ManyToOne
private Gender gender;
[...]
}
还有更多。我现在的任务是将这些实体打印成JSON
目前我使用的是:
public String createJSONFromObject(Object obj)
{
Gson gson = new GsonBuilder().setPrettyPrinting().setExclusionStrategies(new ExcludeProxiedFields()).create();
String json = gson.toJson(obj);
return json;
}
与
public class ExcludeProxiedFields implements ExclusionStrategy{
@Override
public boolean shouldSkipField(FieldAttributes fa) {
return fa.getAnnotation(ManyToOne.class) != null ||
fa.getAnnotation(OneToOne.class) != null ||
fa.getAnnotation(ManyToMany.class) != null ||
fa.getAnnotation(OneToMany.class) != null;
}
}
因为我在尝试序列化这些字段时出错
在排除字段时,是否有方法向JSON添加自定义字段?例如,我想包括外国表的ID
我是否排除了太多?有更清洁的解决方案吗
共 (0) 个答案