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 for 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
Edit: I'm trying to see if it's possible to emulate the behavior of Struts2 JSON plugin
using Gson
<interceptor-ref name="json">
<param name="enableSMD">true</param>
<param name="excludeProperties">
login.password,
studentList.*\.sin
</param>
</interceptor-ref>
Edit: I reopened the question with the following addition:
I added a second field with the same type to futher clarify this problem. Basically I want to exclude country.name
but not countrOfBirth.name
. I also don't want to exclude Country as a type.
So the types are the same it's the actual place in the object graph that I want to pinpoint and exclude.
Or can say whats fields not will expose with:
on your class on attribute:
Another approach (especially useful if you need to make a decision to exclude a field at runtime) is to register a TypeAdapter with your gson instance. Example below:
In the case below, the server would expect one of two values but since they were both ints then gson would serialize them both. My goal was to omit any value that is zero (or less) from the json that is posted to the server.
I solved this problem with custom annotations. This is my "SkipSerialisation" Annotation class:
and this is my GsonBuilder:
Example :
You can explore the json tree with gson.
Try something like this :
You can add some properties also :
Tested with gson 2.2.4.
I have Kotlin version
and how You can add this to Retrofit GSONConverterFactory:
Kotlin's
@Transient
annotation also does the trick apparently.Output: