Need field-specific information in custom JsonSerializer
- Dominant language
- Java
- Stars
- 24.2k
- Forks
- 4.5k
- Avg merge
- 6d 4h
- Merged PRs (30d)
- 12
Description
```
In my use case, I need to truncate some long String to fit the need of mobile
client while still keeping the full String for web.
So I built two separate Gson objects for web and mobile, and specify some
annotation on String field which needs to be truncated:
class Foo {
@MobileJsonTruncate(70)
String message;
}
But in the custom JsonSerializer, I have little information about the field
being serialized, thus I can't get the annotation to determine whether to
truncate and how long to keep.
Ideally, if we have the FieldAttributes information as a parameter of
serialize() method or stored within JsonSerializationContext, that will be a
easy job.
But now, I have to write an ugly work around like this:
class MobileJsonSerializer implements ExclusionStrategy, JsonSerializer
{
@Override
public boolean shouldSkipField(final FieldAttributes aField) {
iField = aField;
return aField.getAnnotation(WebExclusive.class) != null;
}
@Override public JsonElement serialize(final String aSrc, final Type aTypeOfSrc, final JsonSerializationContext aContext) {
final MobileTruncate annotation = iField.getAnnotation(MobileTruncate.class);
if (annotation == null)
return aContext.serialize(aSrc);
final JsonPrimitive result = new JsonPrimitive(aSrc.substring(0, Math.min(aSrc.length(), annotation.value())));
iField = null;
return result;
}
@Override public boolean shouldSkipClass(final Class clazz) { return false; }
private FieldAttributes iField;
}
```
Original issue reported on code.google.com by `oasisfeng` on 1 Apr 2011 at 1:34
Contributor guide
Assessment
This issue has not been assessed yet.