Gson
Using Google's Gson for JSON serialization in JobRunr
Gson, Google’s JSON library, is known for its simplicity and zero-dependency design. It handles most serialization needs out of the box without requiring extensive configuration. JobRunr supports Gson through the GsonJsonMapper implementation.
NoteGson is in maintenance mode, meaning that it may not see any new features.
Installation
Add Gson to your project dependencies. Configuration for other build tools can be found on Maven Central: https://central.sonatype.com/artifact/com.google.code.gson/gson.
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version><!-- latest version --></version>
</dependency>
implementation 'com.google.code.gson:gson' // version omitted, use latest
Usage
JobRunr automatically detects Gson on your classpath and uses it for serialization. When multiple JSON libraries are available, Gson has the fourth-highest priority in the detection hierarchy.
If auto-detection doesn’t work, you can manually configure it:
JobRunr.configure()
.useJsonMapper(new GsonJsonMapper())
//...
.initialize();
import org.jobrunr.utils.mapper.JsonMapper;
@Singleton
public JsonMapper jsonMapper() {
return new GsonJsonMapper();
}
import org.jobrunr.utils.mapper.JsonMapper;
@Produces
public JsonMapper jsonMapper() {
return new GsonJsonMapper();
}
import org.jobrunr.utils.mapper.JsonMapper;
@Bean
public JsonMapper jsonMapper() {
return new GsonJsonMapper();
}
Custom Gson configuration
Customize Gson by creating your own GsonJsonMapper instance. The class offers three constructors depending on your needs.
ImportantBefore proceeding, note that JobRunr may overwrite your custom configuration. Verify through testing that everything behaves as expected.
Using GsonBuilder
Pass a configured GsonBuilder to customize serialization behavior:
var gsonBuilder = new GsonBuilder()
.registerTypeAdapter(MyCustomType.class, new MyCustomTypeAdapter());
var jsonMapper = new GsonJsonMapper(gsonBuilder);
Using a pre-configured Gson instance
If you already have a Gson instance configured elsewhere in your application, you can reuse it:
Gson gson = // ... your existing Gson instance
var jsonMapper = new GsonJsonMapper(gson);
WarningUsing this may prevent JobRunr from functioning properly. Prefer the builder option or make sure that your
Gsoninstance has all the configuration required by JobRunr.
