Jackson is most popular Java library to handle JSON parser, and it is the default choice in Spring Boot.
In the rest services, the Jackson converter will be created automatically and used to convert POJO objects to/from Json.N will be used.
From JSON to POJO, the process is deserialize
, and from POJO to JSON is serialize
.
On top of the default Jackson convertion, we can add customized filter on field bases:
// Only convert the non null value
@JsonInclude(JsonInclude.Include.NON_NULL)
// The filter will be matched by name
@JsonFilter("fooFilter")
public class Foo {
// Ignore specific field from both serialization and deserialization.
@JsonIgnore
private Special specialField
// This field will be skipped from serialization because of the json filter.
private Bar anotherSpecialField
.....
}
public class FooService {
private static ObjectMapper mapper;
public FooService() {
mapper = new ObjectMapper();
FilterProvider filters = new SimpleFilterProvider.addFilter("fooFilter",
SimpleBeanPropertyFilter.serializeAllExcept("anotherSpecialField"));
mapper.setFilterProvider(filters);
}
// Convert using the predefined filters.
private static FooDestination convert(Foo foo) {
return mapper.convertValue(foo, FooDestination.class);
}
}
For some use cases, we will use customized serializer like this.
public class FooSerializer extends JsonSerializer<Foo> {
@Override
public void serialize() {
// what ever logic for the customized convertion
ObjectMapper objectMapper = new ObjectMapper();
foo = objectMapper.writeValueAsString(....);
jsonGenerator.writeString(foo);
}
}
// Usage
@JsonSerialize(using = FooSerializer.class)
public class Foo {
.........
}