I have several JPA Entities like
public class Person implements Serializable
{
@Id
private long id;
@OneToMany(mappedBy = "Person", fetch = FetchType.LAZY)
private List<Adresse> adressen;
@ManyToOne
private Gender gender;
[...]
}
And many many more. I now got the Task to print these Entities to JSON.
Currently i am using this:
public String createJSONFromObject(Object obj)
{
Gson gson = new GsonBuilder().setPrettyPrinting().setExclusionStrategies(new ExcludeProxiedFields()).create();
String json = gson.toJson(obj);
return json;
}
with
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;
}
}
because i got an error, when trying to serialize these Fields.
Is there a way to add a custom Field to the JSON when excluding the Fields? I would like to e.g. include the ID of the foreign Table.
Am I excluding too much? Is there a cleaner Solution?