I was wondering why not include an annotation that allows the exclusion of only a single field or just few fields while serialization.
Example:
Class Test{
String s1;
String s2;
String s3;
String s4;
}
If I want to avoid serializing s1 and want to expose the other fields then it currently would look like :
Class Test{
String s1;
@Expose String s2;
@Expose String s3;
@Expose String s4;
}
But, I think it would be way more easier to have it the following :
Class Test{
**@DoNotExpose** String s1;
String s2;
String s3;
String s4;
}
Can someone please tell if there is a reason for not having this annotation or if there is a cleaner workaround for this available already, as we have a case where we want to avoid serializing a single heavy reference in classes and still expose the other fields.
Use the transient modifier?
@NightlyNexus
The field that we want to avoid is persistent in DB and not transient. So, we can't mark it as transient as then the entity won't persist that field. We only want to avoid that field during serialization/deserialization
@aishydevil12286 It looks like you have to separate DTOs for different layers (if you keep them mixed -- then it might be hell in the future; especially when migrating from one library to another): one for transport/Gson and one for persistence/whatever.
@lyubomyr-shaydariv Though maintaining different classes for different purpose seems a good solution, we would end up in different hell when we have a big application with many classes and wanted to keep the fields in sync and copy data from one object to another.
@arundhaj Then someone would need @SerializeOnly and DeserializeOnly some day. :) It would be nice if Java could support a sort of meta-annotations to compose annotation declarations similarly to what Spring Framework does. Just curious: how many fields do you need to annotate with such an annotation?
@lyubomyr-shaydariv True ;). For an API project which I'm working on, though I have few fields (around 15-20), I have many classes (around 35-40). For now, I use two duplicate classes; one for domain objects and one for API objects. I use API objects only for external interface and domain objects for everything else used internally. Specific to this issue, I'm using User Defined Exclusion Strategy to annotate few fields to @GsonExclude instead of many fields to @Expose.
Most helpful comment
@NightlyNexus
The field that we want to avoid is persistent in DB and not transient. So, we can't mark it as transient as then the entity won't persist that field. We only want to avoid that field during serialization/deserialization