What is the best way to optimize deserialization?
I am currently using the standard Gson.toJson and Gson.fromJson methods for serialization and deserialization of some c
Gson is known and use for it's ease of use. If you want speed you will have to look at the super popular Jackson Json.
I have tested and benchmarked both Gson and Jackson and I can tell you that in some use cases Jackson is 15 times faster on both serialization and deserialization, even on very big objects.
To get similar behavior as Json I use the following settings
public enum JsonMapper {
INSTANCE;
private final ObjectMapper mapper;
private JsonMapper() {
mapper = new ObjectMapper();
VisibilityChecker> visibilityChecker = mapper.getSerializationConfig().getDefaultVisibilityChecker();
mapper.setVisibilityChecker(visibilityChecker
.withFieldVisibility(Visibility.ANY)
.withCreatorVisibility(Visibility.NONE)
.withGetterVisibility(Visibility.NONE)
.withSetterVisibility(Visibility.NONE)
.withIsGetterVisibility(Visibility.NONE));
}
public ObjectMapper mapper() {
return mapper;
}
}
This will turn out to give the exact same json strings as Gson for the same objects. You can set it to use only getters and setters if you want to. I'd advise you to read about all the jackson json annotations for handling subtypes (useful for RPC-style systems).
My use cases : I use jackson as serialization when I need to save blobs to storage systems (Redis, Cassandra, Mongo, ... sometime mysql too). I also use it as the serialization for my RPC-style APIs for fairly high traffic systems, although I prefer using Protobuf for those when possible. In this last case I use Jackson to directly serialize to byte[] or stream for better performance.
One last note : The object mapper is thread safe and having one static instance like in the example I just submitted will prevent you from having the slight instantiation overhead.
EDIT : I am aware that my example doesn't follow a lot of the best practices pointed out in the jackson page but it allows me to have simple to understand code that looks like the Gson.toJson
and Gson.fromJson
(which I started with too and switched on later to Jackson)
Gson.toJson(object)
=> JsonMapper.INSTANCE.mapper().writeValueAsString(object)
Gson.fromJson(object, clazz)
=> JsonMapper.INSTANCE.mapper().readValue(jsonString, clazz);