I am trying to do something which was quite easy in gson. Since I switched to Jackson as serializer, I couldn't figure out how to implement this:
I want to serialize only fields that have been marked by an Annotation. GSON code would be:
class Foo {
@Expose
public String sometext="Hello World";
@Expose
public int somenumber=30;
public float noop=1.0;
...
}
which should result in (JSON)
{
Foo: {
sometext:'Hello World',
somenumber: 30
}
}
(Syntax errors may be ignored - source is just for demonstration)
So what's the Jackson counterpart for gson's @Expose
and new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
?
If you want it just for a specific type you could also just use annotations:
@JsonAutoDetect(
fieldVisibility = Visibility.NONE,
setterVisibility = Visibility.NONE,
getterVisibility = Visibility.NONE,
isGetterVisibility = Visibility.NONE,
creatorVisibility = Visibility.NONE
)
public class Foo {
@JsonProperty
public String sometext="Hello World";
@JsonProperty
public int somenumber=30;
// noop won't get serialized
public float noop= 1.0f;
}
The counterpart for new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
is to initialise an ObjectMapper as follows:
...
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.disable(MapperFeature.AUTO_DETECT_CREATORS,
MapperFeature.AUTO_DETECT_FIELDS,
MapperFeature.AUTO_DETECT_GETTERS,
MapperFeature.AUTO_DETECT_IS_GETTERS);
...
The counterpart for @Expose
is then @JsonProperty
. Using your above example bean:
class Foo {
@JsonProperty
public String sometext="Hello World";
@JsonProperty
public int somenumber=30;
public float noop=1.0;
...
}
See this answer to a very similar question.
There seems to be a way to configure ObjectMapper
to ignore all non annotated fields.
ObjectMapper mapper = new ObjectMapper();
mapper.setVisibilityChecker(getSerializationConfig().getDefaultVisibilityChecker()
.withCreatorVisibility(JsonAutoDetect.Visibility.NONE)
.withFieldVisibility(JsonAutoDetect.Visibility.NONE)
.withGetterVisibility(JsonAutoDetect.Visibility.NONE)
.withIsGetterVisibility(JsonAutoDetect.Visibility.NONE)
.withSetterVisibility(JsonAutoDetect.Visibility.NONE));
Source
In Jackson, you do the inverse. Annotate fields you don't want with @JsonIgnore
.
Marker annotation that indicates that the annotated method or field is to be ignored by introspection-based serialization and deserialization functionality. That is, it should not be consider a "getter", "setter" or "creator".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With