0

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?

recklessGreed
  • 129
  • 10
  • 1
    Read this https://stackoverflow.com/questions/7290777/java-custom-serialization – JLazar0 Aug 25 '20 at 07:56
  • I would suggest you to prefer mapping libraried like mapstruct or modelmapper. They exist to solve this very purpose of adding/hiding values to jsons before being sent back from spring – Sridhar Patnaik Aug 25 '20 at 07:58

0 Answers0