0 votes
1 view
in Java by (10.2k points)

I'm trying to learn Gson and I'm struggling with field exclusion. Here are my classes

public class Student {    

  private Long                id;

  private String              firstName        = "Philip";

  private String              middleName       = "J.";

  private String              initials         = "P.F";

  private String              lastName         = "Fry";

  private Country             country;

  private Country             countryOfBirth;

}

public class Country {    

  private Long                id;

  private String              name;

  private Object              other;

}

I can use the GsonBuilder and add an ExclusionStrategy for a field name like firstName or country but I can't seem to manage to exclude properties of certain fields like country.name.

Using the method public boolean shouldSkipField(FieldAttributes fa), FieldAttributes doesn't contain enough information to match the field with a filter like country.name.

I would appreciate any help with a solution to this problem.

P.S: I want to avoid annotations since I want to improve on this and use RegEx to filter fields out.

Thank you

1 Answer

0 votes
by (46.1k points)

Any fields you don't want to be serialized in general you should use the "transient" conditioner, and this also pertains to JSON serializers (at slightest it does to a some that I have used, including gson).

If you don't need the name to dispense up in the serialized JSON give it a transient keyword, eg:

private transient String name;

More expanded details in the Gson documentation

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...