On Tuesday, July 3, 2012 8:08:01 PM UTC+2, Jean-Marc Spaggiari wrote:
> With the interface ExclusionStrategy it's possible to exclude a field to be serialized based on it's title. But is there a way to filter based on the value?
+1, that's what I just wanted to ask. My case is nearly the same, except for `{sizeLimit: 9223372036854775807}` looking even worse. I don't want to use -1 there as `Long.MAX_VALUE` is the natural choice here, nor I want to use null as `Long` instead of `long`.
On Friday, July 13, 2012 2:14:55 AM UTC+2, Inderjeet Singh wrote:
> You dont have the option to exclude based on the value in an exclusion strategy. Gson tries to achieve efficiency by making decisions to include/exclude fields once per class (while finding its type adapter). Providing you ability to select based on value would run counter to that.
Concerning the efficiency I beg to differ. Sure, excluding fields on the class basis is good for efficiency, but I don't think you lose any when you do an additional check if a field not-excluded on the per-class bases could be excluded based on its value.
> BTW, You can write a custom type adapter for MyData that excludes temperature if it is -1. Is that not a good enough option?
I'd strongly prefer something like
class MyData {
@GsonExcludeIfValue(Long.MAX_VALUE)
private long sizeLimit = Long.MAX_VALUE;
@GsonExcludeIfValue(-1)
private int temperature = -1;
}
or maybe
class MyData {
@GsonDefaultValuesProvider
private static defaultInstance = new MyData();
private sizeLimit = Long.MAX_VALUE;
private int temperature = -1;
}
where each value would be tested against the value in defaultInstance, or maybe
@GsonExcludeDefaultValue
class MyData {
private sizeLimit = Long.MAX_VALUE;
private int temperature = -1;
}
where GSon would determine the default values by deserializing an object with missing values. The last idea mightn't work.